简体   繁体   English

替换JavaScript中所有出现的字符串

[英]Replace All Occurrences Of a String in JavaScript

I have a string as follows 我有一个字符串如下

var company = "Microst+Apple+Google";

And I want replace all the + signs with %2B 我想用%2B替换所有+号

But when I use this code. 但是当我使用这段代码时。 It returns 0 返回0

var company = company.replace(/+/g, "%2B");

I think JavaScript thinks that + is an arithmetic operation. 我认为JavaScript认为+是算术运算。 Is there a special symbol to be used? 是否有特殊符号要使用? or can user a variable except directly using the + sign? 还是可以使用除直接使用+号以外的其他变量? If so please mention. 如果是这样,请提及。 Any Idea how to do this ? 任何想法如何做到这一点?

No, JavaScript doesn't think it's an arithmetic operation but + is a quantifier in regular expressions and the regular expression parser doesn't understand yours. 不,JavaScript认为它不是算术运算,但是+是正则表达式中的量词,而正则表达式解析器无法理解您的表达式。

You must escape the + : 您必须转义+

var company = company.replace(/\+/g, "%2B");

You need escape it : 您需要逃脱它:

var company = company.replace(/\\+/g, "%2B");

It is because + is special symbol used to indicate that preceding character should match 1 or more times. 这是因为+是特殊符号,用于表示前一个字符应匹配1次或更多次。

You can read more about regular expressions syntax here: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions 您可以在此处阅读有关正则表达式语法的更多信息: https : //developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

You can use this : 您可以使用:

var company = company.replace(/\+/g, "%2B");

Or an easier way : 或更简单的方法:

var company = encodeURIComponent(company);

which will do the same operation as the regex one. 它将执行与正则表达式相同的操作。 Also, it encodes all URI chars like & , " (quotes), % etc... if there is one like it in the string given. 另外,如果给定的字符串中有一个类似的字符,它将对所有URI字符进行编码,例如&" (引号), %等...”。

In both cases, the output is : 在这两种情况下,输出均为:

Microst%2BApple%2BGoogle Microst%2BApple%2BGoogle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM