Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用javascript将正斜杠替换为反斜杠和正斜杠_Javascript - Fatal编程技术网

如何使用javascript将正斜杠替换为反斜杠和正斜杠

如何使用javascript将正斜杠替换为反斜杠和正斜杠,javascript,Javascript,我想使用javascript将“/”替换为“\/” 例如: http://www.freeformatter.com/javascript-escape.html 到 你可以做: str.replace(/\//g, "\\/"); 其中str是保存字符串值的变量 演示:使用替换: "http:/www.freeformatter.com/javascript-escape.html".replace(/\//g, "\\/"); 如果变量中有字符串: var url = "http:/w

我想使用javascript将“/”替换为“\/”

例如:

http://www.freeformatter.com/javascript-escape.html

你可以做:

str.replace(/\//g, "\\/");
其中
str
是保存字符串值的变量

演示:

使用替换:

"http:/www.freeformatter.com/javascript-escape.html".replace(/\//g, "\\/");
如果变量中有字符串:

var url = "http:/www.freeformatter.com/javascript-escape.html";
url.replace(/\//g, "\\/");
这里可以使用str.replace()和正则表达式对象。基本上,您只需要转义替换字符串中的转义字符

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

你在什么情况下使用这个?您是否试图手动解救JavaScript字符串?请考虑扩展您的答案来解释ASKER为什么要达到预期的结果,可能会链接到文档。照目前的情况,这只是一点用处。
str = str.replace(new RegExp('/','g'),"\\/");