In JavaScript, you can remove trailing slashes from a string in the following ways:
- Using
endsWith()
; - Using a Regular Expression With
replace()
; - Using Bracket Notation;
- Using
substr()
; - Using
charAt()
;
Using endsWith()
Introduced in ES6, you can use endsWith()
to see if the string ends with a trailing slash, and accordingly you 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). You 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 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
You 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;
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.