Explain Codes LogoExplain Codes Logo

How to remove the first and the last character of a string

javascript
string-manipulation
javascript-methods
regular-expressions
Nikita BarsukovbyNikita Barsukov·Sep 28, 2024
TLDR

Trim the first and last characters of a string in JavaScript using slice method:

let str = "Example"; let trimmed = str.slice(1, -1); // Shaved down to "xampl" - bye-bye, "E" and "e"!

slice(1, -1) leaves out the first and last contestant in the string race, yielding a slightly less 'Example-y' string.

Slice vs. substring vs. substr

The JavaScript substring method also lets you cut out the first and last characters. While the slice method uses negative index for the last characters, the substring method would rely on the length of the string minus one:

let str = "Example"; let substrTrimmed = str.substring(1, str.length - 1); // Awkwardly sizes up the string and brings out the scissors

As for substr, it's worth a mention but it has sadly been declared obsolete (cue small violin). substr also takes a starting point but, akin to a confused party guest, requests the actual length of the substring after the start. This often leads to awkward silences, and it's generally best to let substr retire gracefully.

Regular Expressions (RegExp)

For those who like to strut around ignored edge cases, JavaScript's regular expressions can serve as a more powerful tool than slice or substring.

let str = "/Example/"; let regexTrimmed = str.replace(/^.|.$/g, ''); // That macho regex walked in, assuming it knows better than everyone.

RegEx, or RegExp, employs a robust pattern search and replace, making it the JavaScipt's bouncer, throwing out the unwanted characters at the beginning (^.) or the end (.$).

Tackling special cases

Be cautious when the string might start or end with special characters. RegEx becomes even more vital:

let url = "/example/"; let cleanUrl = url.replace(/^\/?|\/?$/g, ''); // Regex, the doorkeeper again, checking for fake IDs (slashes) at the door.

This pattern considers optional slashes at the start and the end, eliminating them if found. After all, you don't want false positives causing trouble in your string club.

Rounding-up the alternatives

JavaScript comes loaded with trim, a method which, while not directly removing specific characters, can be quite voracious when it comes to stripping whitespace from both ends:

let str = " A little less lonely "; let whitespaceTrimmed = str.trim(); // Trim, acting like a desperate weightwatcher on a diet...

Remember, different strokes for different folks!