javascript 如何全局替换管道符号“|” 在字符串中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29593532/
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-10-28 10:45:54  来源:igfitidea点击:

How to globally replace pipe symbol "|" in string

javascriptregex

提问by user2837849

How can I globally replace the |(pipe) symbol in a string? When I try to replace it with "so|me|str|ing".replace(/|/g, '-'), I get "-s-o-|-m-e-|-s-t-r-|-i-n-g-"

如何全局替换|字符串中的(管道)符号?当我尝试用 替换它时"so|me|str|ing".replace(/|/g, '-'),我得到"-s-o-|-m-e-|-s-t-r-|-i-n-g-"

回答by joews

|has special meaning(A|Bmeans "match A or B"), so you need to escape it:

|具有特殊含义A|B表示“匹配 A 或 B”),因此您需要对其进行转义:

"so|me|str|ing".replace(/\|/g, '-');

回答by squill25

|means OR, so you have to escape it like this: \|

|意味着OR,所以你必须像这样逃避它:\|

回答by ChadF

Try using "so|me|str|ing".replace(/[|]/g, '-')

尝试使用 "so|me|str|ing".replace(/[|]/g, '-')

This is a great resource for working with RegEx: https://www.regex101.com/

这是使用 RegEx 的绝佳资源:https: //www.regex101.com/

回答by Devdatta Tengshe

In my case, the pipe was coming as an variable, so I couldn't use any of these solutions. Instead, You can use:

就我而言,管道是作为变量出现的,因此我无法使用任何这些解决方案。相反,您可以使用:

let output_delimiter  ='|';
let str= 'Foo|bar| Test';

str.replace(new RegExp('[' + output_delimiter + ']', 'g'), '-')

//should be 'Foo-bar- Test'