如何替换 JavaScript 中的加号?

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

How can I replace a plus sign in JavaScript?

javascriptregexescaping

提问by William Calleja

I need to make a replace of a plus sign in a javascript string. there might be multiple occurrence of the plus sign so I did this up until now:

我需要替换 javascript 字符串中的加号。加号可能会多次出现,所以直到现在我才这样做:

myString= myString.replace(/+/g, "");#

This is however breaking up my javascript and causing glitches. How do you escape a '+' sign in a regular expression?

然而,这会破坏我的 javascript 并导致故障。如何在正则表达式中转义“+”号?

回答by Darin Dimitrov

myString = myString.replace(/\+/g, "");

回答by codaddict

You need to escape the +as its a meta char as follows:

您需要将 转义+为元字符,如下所示:

myString= myString.replace(/\+/g, "");

Once escaped, +will be treated literally and not as a meta char.

一旦转义,+将按字面意思处理,而不是作为元字符处理。

回答by David

I prefer this:

我更喜欢这个:

myString.replace(/[+]/g, '').

回答by ghostdog74

you should escape your +sign, \+

你应该逃避你的+标志,\+

回答by Marko Dumic

myString.replace(/\+/g, "");