Sometimes, we want to globally replace a forward slash in a JavaScript string.
In this article, we’ll look at how to globally replace a forward slash in a JavaScript string.
How to globally replace a forward slash in a JavaScript string?
To globally replace a forward slash in a JavaScript string, we call the string replace
method with a regex with the g
flag.
For instance, we write
const s = "/string/".replace(/\//g, "ForwardSlash");
to call '/string/'.replace
with the regex /\//g
and 'ForwardSlash'
to replace the forward slashes in '/string/'
with 'ForwardSlash'
.
Conclusion
To globally replace a forward slash in a JavaScript string, we call the string replace
method with a regex with the g
flag.