This article will illustrate the methods to trim characters from the end of a string in JavaScript.
How to Trim Character From End of the String in JavaScript?
To trim characters from the end of the string in JavaScript, the following methods can be applied:
- “substring()” Method.
- “slice()” Method.
Check out the above-mentioned methods one by one!
Method 1: Trim a Character From the String’s End in JavaScript Using substring() Method
The “substring()” method extracts characters from the start till the end without any change in the original string value. This technique can be applied to trim the last string character by removing the last element using the “length” property.
Syntax
Here, “start” refers to the start index, and “end” refers to the end index of the given string.
The following example will demonstrate the explained concept.
Example
Firstly, a variable named “trimLast” is created having the following value:
Now, the “substring()” method will be applied to trim the last character. This will be done by specifying the index of the first string character as “0”. For the last index, the “length” property will be utilized, and “1” will be subtracted from it to trim the last string character:
Finally, the updated string value will be displayed on the console:
It can be seen that the last “d” is trimmed from the given string:
Method 2: Trim Character From End of String in JavaScript Using slice() Method
The “slice()” method slices up the selected items and gives a new array of the particular items. This method can be utilized to trim the last string character by referring to the index of the last character and slicing it.
Syntax
In the above syntax, “start” is the start index, and “end” refers to the last index.
The following example explains the above concept.
Example
We will consider the already created string. Now, the “slice()” method will be applied with “0” referring to the first string character and “-1” as the last string character. This method will work in such a way that the “-1” index will slice the last string character, and a new string value will be returned:
Lastly, the updated string value after trimming will be logged on the console:
Output
We have compiled different approaches for trimming characters from the end of String in JavaScript.
Conclusion
To trim characters from the end of the string in JavaScript, the “substring()” method can be applied along with the “length” property to refer to the string’s total length and subtract the last character value from it or the “slice()” method to refer to the index position of the last string character and slice it accordingly. This blog explained the methods to remove characters from the string’s end in JavaScript.