简体   繁体   中英

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

But when I use this code. It returns 0

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

I think JavaScript thinks that + is an arithmetic operation. 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.

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.

You can read more about regular expressions syntax here: 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.

In both cases, the output is :

Microst%2BApple%2BGoogle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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