Use the slice() method with 0
for the start index and -2
the end index as parameters to Remove the last 2 characters from the string in JavaScript.
str.slice(0, -2);
This method returns a new string containing the extracted section of the original string.
Note: Passing an end index parameter of -2
and str.length - 2
is the same.
Remove the last 2 characters from the string JavaScript
Simple example code.
<!DOCTYPE html>
<html lang="en">
<body>
<script>
const str = 'Hello io';
const res = str.slice(0, -2);
console.log(res);
console.log("Original", str)
</script>
</body>
</html>
Output:
slice
is a method that extracts a section of a string and returns it as a new string.- The first parameter (
0
) indicates the start index, which is the beginning of the string. - The second parameter (
-2
) indicates the end index, which is 2 characters from the end of the string. Negative indices count back from the end of the string.
Alternative method
You can use substring()
method on the string to remove the last 2 characters from a string by passing it 0
for the start index and str.length - 1
for the end index as parameters.
const str = 'one two';
const res = str.substring(0, str.length - 2);
console.log(res); // one t
More examples
let str = "12345.00";
str = str.substring(0, str.length - 2);
console.log(str); //12345.
Do comment if you have any doubts or suggestions on this JS remove char code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version