[Solved] javascript replace \/ or /\ to single slash /


Because a backslash is used as an escape character, you’ll need to escape it:

str = str.replace("\\/", "https://stackoverflow.com/");

The above replaces \/ with /. In general, anywhere you use a backslash in a string, you probably need to escape it. So, to replace /\ with /, you’d use:

str = str.replace("/\\", "https://stackoverflow.com/");

These will, of course, only replace one instance in the string. To replace multiple instances, use a regular expression with the g (global) modifier:

str = str.replace(/\\\/|\/\\/g, "https://stackoverflow.com/")

Here, because forward slashes have meaning as regex terminators, you’re having to escape the forward slash as well as the backslash. The alternative is to use the RegExp class:

str = str.replace(new RegExp("\\\\/|/\\\\", "g"), "https://stackoverflow.com/")

In this one, you’re having to escape the backslash twice — once to escape it in the string, and once in the regex. (Here’s a better explanation.)

solved javascript replace \/ or /\ to single slash /