How to globally replace a forward slash in a JavaScript string ?
To globally replace a forward slash in a JavaScript string, you can use the replace()
method with a regular expression and the global flag (g
).
Here are some examples:
- Using the
replace()
method with a regular expression:
let str = "This/is/a/test";
let newStr = str.replace(/\//g, "-");
console.log(newStr); // "This-is-a-test"
In this example, the regular expression /\/g
matches all forward slashes in the string str
, and the replace()
method replaces them with hyphens.
- Using the
split()
andjoin()
methods:
let str = "This/is/a/test";
let newStr = str.split("/").join("-");
console.log(newStr); // "This-is-a-test"
In this example, the split()
method splits the string str
into an array of substrings at each forward slash, and the join()
method joins the array elements with hyphens to create the new string.
Both methods achieve the same result, but the first method is more flexible if you need to replace other characters or use more complex regular expressions.