JavaScript - How to Globally Replace a Forward Slash in a String?
Here are the various methods to globally replace a forward slash in the JavaScript string.
1. Using replace() Method with a Regular Expression
The replace() method is commonly used with a regular expression to replace all occurrences of a forward slash.
const s1 = "path/to/some/resource";
const s2 = s1.replace(/\//g, "-");
console.log(s2);
Output
path-to-some-resource
- The /\//g pattern matches all forward slashes.
- The g flag ensures the replacement is global.
2. Using replaceAll() Method
For modern JavaScript, replaceAll() provides a simpler syntax for replacing all forward slashes without the need for regular expression.
const s1 = "path/to/some/resource";
const s2 = s1.replaceAll("/", "-");
console.log(s2);
Output
path-to-some-resource
This method is concise, but it requires ES2021 or later.
3. Using split() and join() Method
An alternative approach involves splitting the string into an array and joining it back with the desired replacement.
const s1 = "path/to/some/resource";
const s2 = s1.split("/").join("-");
console.log(s2);
Output
path-to-some-resource
This method is simple and effective for replacing forward slashes globally, especially in older environments where replaceAll() is not supported.
4. Using Array.prototype.map() Method
You can also convert the string to an array, use map() for replacement, and then join it back into a string.
const s1 = "path/to/some/resource";
const s2 = [...s1].map((char) =>
(char === "/" ? "-" : char)).join("");
console.log(s2);
Output
path-to-some-resource
5. Using reduce() Method
The reduce() method can also be used for global replacements.
const s1 = "path/to/some/resource";
const s2 = [...s1].reduce((acc, char) =>
acc + (char === "/" ? "-" : char), "");
console.log(s2);
Output
path-to-some-resource
Which Approach Should You Use?
Approach | When to Use |
---|---|
Using replace() with Regex | Best for compatibility and handling patterns or advanced replacements. |
Using replaceAll() | Ideal for modern JavaScript with clean, readable syntax. |
Using split() and join() | Great for environments without replaceAll() or when avoiding regex. |
Using a Loop | Suitable for educational purposes or custom logic. |
Using Array.prototype.map() | Useful when you need to transform the string while replacing. |
Using reduce() | Best for functional programming scenarios or combining transformations. |
While the first three methods (replace(), replaceAll(), and split() + join()) cover most use cases, using functional methods (map() or reduce()) can be helpful in specific situations where additional processing is required.