Show of hands if you can off of the top of your head remove/trim a character from the start or end of a string. If your hand remained down, don’t feel too bad. There are so many string manipulation methods in Javascript, it can be confusing.
We have; substr
, substring
and splice
(just off the top of my head). Not many people can tell you the differences between the three without Googling.
In this weeks lesson of, “You probably already know this, but some people might not”, we are going to be removing characters from the beginning and end of strings. Riveting stuff, right?
You didn’t come here for a lesson, so let’s just jump right into some code, shall we? The only two methods you need to know are substr
and slice
the rest, not so much. Although, always make sure you test any code that you just find on a random blog like this.
Remove the first character
Want to remove the first character from a string? Just bump the number up if you want to remove more than one character from the beginning of the string.
var myString = '!thisIsMyString';
var sillyString = myString.substr(1);
If you wanted to remove say 5 characters from the start, you’d just write substr(5)
and you would be left with IsMyString
using the above example.
Remove the last character
To remove one character off of the end of a string, we can use the String.slice
method. The beautiful thing about slice is it accepts negative numbers, so we don’t need to calculate the length like many other solutions seem to use for whatever reason. You don’t need to calculate the string length to remove a character and or characters off of the end.
var myString = 'thisIsMyString!';
var sillyString = myString.slice(0, -1);
Remove the first character and last character
What if you wanted to remove a character from the beginning of a string as well as from the end at the same time? Because of the way string methods work, they are chainable.
var myString = '!thisIsMyString!';
var sillyString = myString.substr(1).slice(0, -1);