EN
JavaScript - remove last 3 characters from string
3
points
In this article, we're going to have a look at how to remove the last 3 characters from the string in JavaScript.
1. String slice() method example
This approach allows getting substring by using negative indexes. So by using 0 and -3 indexes as the range we get <0, text.length - 3> text range.
// ONLINE-RUNNER:browser;
var text = 'abcde';
var substring = text.slice(0, -3);
console.log(substring); // ab
2. String substring() method example
This is an alternative approach to slice method based solution.
// ONLINE-RUNNER:browser;
var text = 'abcde';
var substring = text.substring(0, text.length - 3);
console.log(substring); // ab
3. String replace() method example
There is another trick that allows replacing all characters that match expression condition. By using .{0,3}$ pattern we match any 3 characters (up to 3 characters) that are located at the end of the string.
// ONLINE-RUNNER:browser;
var text = 'abcde';
var substring = text.replace(/.{0,3}$/, '');
console.log(substring); // ab