开发者

Regex to replace all '&' which are in " " in a string....in javascript

开发者 https://www.devze.com 2023-02-09 04:27 出处:网络
I have url in which the parameters contain \'&\' characters ..now i have to do an ajax call but the server sends exception on that..so the soluti开发者_运维百科on is to replace the \'&\' of pa

I have url in which the parameters contain '&' characters ..now i have to do an ajax call but the server sends exception on that..so the soluti开发者_运维百科on is to replace the '&' of parameters by %26 and then make the call...

e.g...

url = http://localhost.com/?q=java&industry="IT&web"&location="New-york & Florida"

The result must be...

= http://localhost.com/?q=java&industry="IT%26web"&location="New-york %26 Florida"


You must use:

query = encodeURIComponent (query);


If you're stuck with this string and want to try to encode it:

var url = "http://localhost.com/?q=java&industry=\"IT&web\"&location=\"New-york & Florida\"";

One option is to capture all quoted expressions (assuming they match, of course), and apply encodeURIComponent on them. The result is having the whole parameter encoded, including the quotes:

url = url.replace(/"[^"]*"/g, encodeURIComponent);
> http://localhost.com/?q=java&industry=%22IT%26web%22&location=%22New-york%20%26%20Florida%22

Similarly, you can replace only the ampersands if that's what you need:

url = url.replace(/"([^"]*)"/g, function(g0){return g0.replace(/&/g, encodeURIComponent);});
> http://localhost.com/?q=java&industry="IT%26web"&location="New-york %26 Florida"

In both cases, this may clash with already-escaped characters, so again, the best solution is to fix the problem at its source, where the url is created.

0

精彩评论

暂无评论...
验证码 换一张
取 消