JavaScript – Remove Last Character of String
To remove last character of the given string in JavaScript, call slice()
method on the string, and pass the starting position 0
and ending position string length - 1
as arguments to it.
slice() method takes the starting position and ending position of the required resulting string as arguments, and returns the sliced string.
The syntax of the expression to remove the last character from the string str
using slice()
method is
str.slice(0, str.length - 1)
slice()
returns the resulting sliced string, and does not modify the original string.
Examples
In the following example, we take a string str
, remove the last character using slice()
method, and display the original and resulting string in pre#output.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var str = '12345678#';
var result = str.slice(0, str.length - 1);
var output = 'Original string : ' + str;
output += '\n\nResult string : ' + result;
document.getElementById('output').innerHTML = output;
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned how to remove the last character of given string in JavaScript, using slice() method, with examples.