How to Remove a Trailing Slash From a String in JavaScript?

Learn different ways of removing a trailing slash from a JavaScript string

Using endsWith():

Introduced in ES6, we can use endsWith() to see if the string ends with a trailing slash and accordingly we can remove it. For example:

// ES6+
str.endsWith('/') ? str.slice(0, -1) : str;
str.endsWith('/') ? str.substr(0, str.length - 1) : str;

Using a Regular Expression With replace()

Regular expressions are very well supported across all browsers (new and old). We can use a regular expression with str.replace() to remove a trailing slash without the need to first explicitly check if a trailing slash exists and then remove it (as we do in the other methods). Also, this may be a choice, if you're looking for a one-liner. For example:

str.replace(/\/$/, '');

Using Bracket Notation:

We can use the bracket notation to access the last character of the string and then replace it accordingly like so:

(str[str.length - 1] === '/') ? str.slice(0, -1) : str;
(str[str.length - 1] === '/') ? str.substr(0, str.length - 1) : str;

Using substr():

This method has great browser support. If backward compatibility is of concern, then you may want to consider this approach of checking and removing a trailing slash from a string. For example:

(str.substr(-1) === '/') ? str.slice(0, -1) : str;
(str.substr(-1) === '/') ? str.substr(0, str.length - 1) : str;

Using charAt():

Similar to substr(), this method too has great browser support. If backward compatibility is of concern, then may consider this approach of checking and removing a trailing slash from a string. For example:

(str.charAt(str.length - 1) === '/') ? str.slice(0, -1) : str;
(str.charAt(str.length - 1) === '/') ? str.substr(0, str.length - 1) : str;

Hope you found this post useful. It was published . Please show your love and support by sharing this post.