开发者

JavaScript replace all / with \ in a string?

开发者 https://www.devze.com 2023-01-19 03:39 出处:网络
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 transforms it to a UNC

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 transforms it to a UNC path.

ex: http://mysite.com/document1.htm to \myserver\document1.htm

However, I can't seem to get the /'s to goto \'s and am at a loss why.

I've tried 2 things basically

1) str = str.replace(/\/g, "\\");
2) str =开发者_JAVA百科 str.replace("/", "\\");

Any idea why it wont work?

Thanks, Dave


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消