Skip to main content

How to Remove a Trailing Slash from a String in JavaScript

When working with URLs, file paths, or API endpoints, you often need to standardize them by removing any trailing slashes. This ensures that a path like https://example.com/about/ is treated the same as https://example.com/about, preventing potential issues with routing or duplicate content.

This guide will demonstrate the two best methods for this task. We'll cover the most robust and flexible approach using the String.prototype.replace() method with a regular expression, as well as a simpler method using String.prototype.endsWith() for cases where you only need to remove a single trailing slash.

This is the most powerful and reliable method because it can handle both single and multiple trailing slashes (e.g., path/ and path///) in one simple command.

For example, you have a string that might end with one or more slashes, and you want to remove them all.

// Problem: Clean up these strings to remove trailing slashes.
const path1 = 'https://example.com/path/';
const path2 = 'https://example.com/path///';
const path3 = 'https://example.com/path'; // Should remain unchanged.

The solution uses the replace() method with a regular expression that specifically targets one or more slashes at the end of the string.

function removeTrailingSlash(str) {
// Use a regular expression to find one or more slashes at the end of the string
// and replace them with an empty string.
return str.replace(/\/+$/, '');
}

// Example Usage:
console.log(removeTrailingSlash('https://example.com/path/')); // Output: https://example.com/path
console.log(removeTrailingSlash('https://example.com/path///')); // Output: https://example.com/path
console.log(removeTrailingSlash('https://example.com/path')); // Output: https://example.com/path

An Alternative Method: endsWith() and slice()

If you are certain that your string will have at most one trailing slash, this method is very readable and does not require a regular expression.

The logic:

  1. Check if the string endsWith('/').
  2. If it does, use slice(0, -1) to return a new string containing everything except the last character.
  3. If it doesn't, return the original string.

Solution: this can be written concisely using a ternary operator.

function removeTrailingSlash(str) {
return str.endsWith('/') ? str.slice(0, -1) : str;
}

// Example Usage:
console.log(removeTrailingSlash('https://example.com/path/')); // Output: https://example.com/path
console.log(removeTrailingSlash('https://example.com/path')); // Output: https://example.com/path

// Limitation: This method fails to remove multiple trailing slashes.
console.log(removeTrailingSlash('https://example.com/path///')); // Output: https://example.com/path//
note

Because of this limitation, the replace() method with a regular expression is generally the superior and safer choice.

How the Regular Expression Method Works

The regular expression /\/+$/ is the key to the recommended method. Let's break it down:

  • / ... /: These are the delimiters that mark the beginning and end of the regular expression pattern.
  • \/: The forward slash character. It must be escaped with a backslash (\) because the forward slash is also used as the delimiter for the regex itself.
  • +: This is a "quantifier." It matches the preceding character (the /) one or more times. This is what allows it to handle both / and ///.
  • $: This is an "anchor." It asserts that the pattern must occur at the end of the string.

So, /\/+$/ translates to: "Find one or more forward slashes that are located at the very end of the string." The replace() method then replaces this match with an empty string, effectively deleting it.

A Note on Immutability

It's important to remember that strings in JavaScript are immutable. Methods like replace() and slice() do not change the original string. They always return a new, modified string.

const originalString = 'path/';
const newString = originalString.replace(/\/+$/, '');

console.log(newString); // Output: path
console.log(originalString); // Output: path/ (The original is unchanged)
note

You must always assign the result of the replace() method to a new variable or reassign it to the original one.

Conclusion

Normalizing URLs and paths by removing trailing slashes is a simple but important task.

  • The replace(/\/+$/, '') method is the recommended best practice. It is robust, concise, and correctly handles both single and multiple trailing slashes.
  • The endsWith() and slice() method is a readable alternative for the simple case of removing a single trailing slash, but it is not as comprehensive.

For most real-world applications, the regular expression approach provides the reliability and flexibility you need.