Javascript 用管道替换字符串中的所有反斜杠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7015188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:16:16  来源:igfitidea点击:

Replace all backslashes in a string with a pipe

javascriptregex

提问by Nate

I have the string: \rnosapmdwq\salesforce\R3Q\OutputFiles\Archive

我有字符串:\rnosapmdwq\salesforce\R3Q\OutputFiles\Archive

I'm getting a unrecognized escape sequence when I try to send this to a .NET web service.

当我尝试将其发送到 .NET Web 服务时,我收到了无法识别的转义序列。

I'm trying to replace all of the "\" with "|" to send it to the server.

我试图用“|”替换所有的“\” 将其发送到服务器。

I know I can use the replacemethod but that only replaces the first element. I think I need to use a regular expression to solve it.

我知道我可以使用replace方法,但这只能替换第一个元素。我想我需要使用正则表达式来解决它。

Here's what I have so far:

这是我到目前为止所拥有的:

Path = Path.replace("\/g", "|");

This is wrong though.

然而这是错误的。

回答by Griffin

You don't need to make a regex a string, and it helps having that first /in there

你不需要做一个正则表达式的字符串,它可以帮助具有先/在那里

Path = Path.replace(/\/g, "|")

回答by RobB

The correct syntax would be: Path = Path.replace(/\\/g, "|");

正确的语法是: Path = Path.replace(/\\/g, "|");

Working example at: http://jsfiddle.net/eDKej/.

工作示例:http: //jsfiddle.net/eDKej/

Example (extra code for demonstration purposes only):

示例(仅用于演示目的的额外代码):

var Path = $("#path").text();
Path  = Path.replace(/\/g, "|");
$("#new-path").append(Path);