To remove the last character from a string in JavaScript, use str.slice(0, -1). Strings in JavaScript are immutable, so .slice(0, -1) returns a new string without modifying the original, and safely returns "" when called on an empty or single-character string.
1. Removing the Last Character with .slice(0, -1)
Pass 0 as the start index and -1 as the end index to stop one character before the end of the string:
function dropLastChar(str) {
if (typeof str !== "string") {
throw new TypeError("Expected a string");
}
return str.slice(0, -1);
}
console.log(dropLastChar("hello!")); // "hello"
console.log(dropLastChar("a")); // ""
console.log(dropLastChar("")); // ""
2. Trailing Delimiters and Unicode / Surrogate Pair Caveats
Depending on your data, two extra details can matter:
-
Removing a trailing delimiter only when present (e.g., a comma or slash): Use a conditional check or
.replace(/,$/, "")when you only want to strip a specific trailing character rather than unconditionally dropping whatever character is last:const csvLine = “apple,banana,cherry,”; const cleanedLine = csvLine.replace(/,$/, “”); console.log(cleanedLine); // “apple,banana,cherry”
-
Unicode emojis or surrogate pairs:
.slice(0, -1)operates on UTF-16 code units, so slicing a string ending with a surrogate-pair emoji (such as"abc😀") leaves a half-surrogate ("abc\uD83D"). When Unicode code points or grapheme clusters matter, iterate with[...str]orIntl.Segmenter:const emojiText = “abc😀”; const withoutLastCodePoint = […emojiText].slice(0, -1).join(“”); console.log(withoutLastCodePoint); // “abc”
3. Common Traps to Avoid
- Using
.substring(0, str.length - 1)on empty strings: For"",str.length - 1is-1, and"".substring(0, -1)clamps-1to0returning""—still safe, though.slice(0, -1)is shorter and more idiomatic. - Using
.pop()on a string: Strings do not have a.pop()method; calling"abc".pop()throws aTypeError. - Assuming strings mutate in place:
const next = str.slice(0, -1)leavesstrunchanged; always capture the returned string.
TL;DR: Use str.slice(0, -1) to return a new string with the last character removed, use .replace(/<char>$/, "") when stripping a specific trailing character conditionally, and watch out for UTF-16 surrogate pairs on emojis.
Are you trimming a trailing delimiter like a comma or slash, handling text with emojis/Unicode characters, or normalizing input strings?
