Trimming off the last character in a JavaScript string is something that we’ve to do often.
In this article, we’ll look at how to trim off the last character in a JavaScript string.
String.prototype.substring
We can use the substring
method available in a string instance to return a substring of the string it’s called on.
For instance, we can use it by writing:
let str = "abc";
str = str.substring(0, str.length - 1);
console.log(str);
We have the str
string which we want to remove the last character from.
Then we call substring
with the start and end indexes which we want to extract from.
Then we assign the returned value back to str
.
The end index itself is excluded from the string, so we need to subtract one from the end index we want to extract the substring we want.
Therefore, str
is 'ab'
in the last line of the code.
String.prototype.slice
A string also comes with the slice
method.
For instance, we can write:
let str = "abc";
str = str.slice(0, -1);
console.log(str);
slice
also takes the start and end indexes respectively.
But we can use the negative indexes which start with -1 for the last character, -2 for the 2nd last character, and so on.
Like with substring
, slice
excludes the character at the end index from the returned string.
Therefore, we get the same result with slice
we we do with substring
.
slice with lastIndexOf
The lastIndexOf
method returns the last index of a given character.
So we can write:
let str = "abc";
str = str.slice(0, str.lastIndexOf("c"));
console.log(str);
We pass 'c'
to lastIndexOf
to get the last index of the str
string.
So we see 'ab'
as the value of str
in the last line.
The split, pop, and join Methods
Also, to remove the last character from a JavaScript string, we can split the string into an array, then call pop
to remove the last item from the array, then use join
to join the character array back into a string.
To do this, we write:
let str = "abc";
const strArr = str.split("")
strArr.pop();
str = strArr.join('')
console.log(str);
We call split
with an empty string to split str
into an array of characters and we store that in strArr
.
Then we call pop
on strArr
to remove the last element from strArr
.
And then we call join
to combine the character array back to a string.
Since strings are iterable objects, we can just use the spread operator to spread it into a string.
For instance, we can write:
let str = "abc";
const strArr = [...str]
strArr.pop();
str = strArr.join('')
console.log(str);
Conclusion
There are many ways to trim off the last character from a string with JavaScript.