Skip to content Skip to sidebar Skip to footer

Javascript Replace All / With \ In A String?

I have a javascript file that is ran through a windows job using cscript. However, I can't seem to fix this thing to work correctly. Inside the file, it basically takes a URL and

Solution 1:

It's like this:

str = str.replace(/\//g, "\\");

the / on the end is the normal /pattern/ format, you need an extra for your \ escape, you can test it out here.

Solution 2:

You can use the following trick:

str = str.split("/").join("\\");

More generally:

function replaceAll(str, a, b) {
    return str.split(a).join(b);
}

This avoids regular expression nightmares.

Post a Comment for "Javascript Replace All / With \ In A String?"