Languages
[Edit]
EN

JavaScript - remove suffix from string

0 points
Created by:
Aisha
418

In this article, we would like to show you how to remove suffix from string in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

let text = 'ABCD';

// replace the last two characters with empty string
let result1 = text.replace(/.{0,2}$/, '');

// remove the last two characters
let result2 = text.slice(0, -2);

// remove the last two characters
let result3 = text.substring(0, text.length - 2);

console.log(result1);  // AB
console.log(result2);  // AB
console.log(result3);  // AB

 

Practical examples

1. String.prototype.replace() with regex

In this example, we use replace() method with regex to replace the last two letters (CD) with an empty string.

// ONLINE-RUNNER:browser;

let text = 'ABCD';

// replace the last two characters with empty string
let result = text.replace(/.{0,2}$/, '');

console.log(result);  // AB

2. String.prototype.slice()

In this example, we use slice() method to remove the last two letters from the text.

// ONLINE-RUNNER:browser;

let text = 'ABCD';

// remove the last two characters
let result = text.slice(0, -2);

console.log(result);  // AB

3. String.prototype.substring()

In this example, we use substring() method to remove the last two letters from the text.

// ONLINE-RUNNER:browser;

let text = 'ABCD';

// remove the last two characters
let result = text.substring(0, text.length - 2);

console.log(result);  // AB

References

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - remove suffix from string

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join