substr() to do this task.
substring() function returns the part of the string between the specified indexes. This function takes two arguments, the starting point of the substring, and the ending point of the substring. 0 as the starting point, and the length of the original string minus 1 as the ending point. This will return the original string minus the last character of the string.
var str= "Hello World!"; var newstr = str.substring(0, str.length - 1); console.log(newstr);
slice() function works similarly. This method extracts the text from a string between the specified indexes and returns a part of the substring.
The first argument is the index where to begin the extraction. However, the second argument is optional where to end the extraction. You can see a negative number to select from the end of the string.
You can use the following code to remove the last character from the string.
var str= "Hello World!"; var newstr = str.slice(0, -1); console.log(newstr);
We prefer to use the
slice() function to remove the last character from the string.
substr() method returns a part of the string, starting at the specified index and extracting the specified number of characters.
var str= "Hello World!"; var newstr = str.substr(0, str.length - 1); console.log(newstr);
As you see above both functions syntax, the difference is in the second argument. The second argument to
substring() is the index to the end of extracting, but the second argument to
substr() is the maximum length to return.
Icon credit: Samat Odedara
If you like our article, please consider buying a coffee for us.
Thanks for your support!
Buy me a coffee!