[英]JavaScript Replace String with a Character |
when I try the following it doesn't work: str.replace("| stuff", "")
当我尝试以下操作时,它不起作用:
str.replace("| stuff", "")
But if I remove the PIPE it does? 但是,如果我删除PIPE,它会这样做吗?
str.replace("stuff", "")
Why doesn't the JS function allow for the PIPE | 为什么JS函数不允许使用PIPE | ?
? What can I do to do a replace that includes a pipe?
我该怎么做才能更换包括管道?
Because .replace
accepts a RegExp, and |
因为
.replace
接受RegExp,所以|
is a special character in RegExp. 是RegExp中的特殊字符。 You need to escape it.
您需要逃脱它。
For example, use str.replace(/\\|/g, "")
to remove every |
例如,使用
str.replace(/\\|/g, "")
删除每个|
character. 字符。
No, it should be working, unless you use /| stuff/
不,它应该可以正常工作,除非您使用
/| stuff/
/| stuff/
or RegExp("| stuff")
instead of "| stuff"
/| stuff/
或RegExp("| stuff")
代替"| stuff"
"xyz| stuff".replace("| stuff", ""); //returns xyz
是不是
"xyz| stuff".replace("\| stuff", ""); //returns xyz
str.replace("| stuff", "")
should work but will only replace the first occurrence. str.replace("| stuff", "")
应该可以工作,但只会替换第一个匹配项。 If you want to replace all of them, try a using a regex like str.replace(/\\|\\sstuff/g, "")
如果要替换所有它们,请尝试使用正则表达式,例如
str.replace(/\\|\\sstuff/g, "")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.