简体   繁体   中英

Issue while trying to replace url in javascript due to special chars

I need to replace a value in a template using js, but I'm having a problem because there is a "$" char in this url that is messing up with everything.

Here is the code sample:

 var url = "http://s7d3.scene7.com/is/image/LuxotticaRetail/8053672035704_shad_fr?$jpegdefault$&wid=45" var template = '<img class="thumb-img" src="{{image_thumb}}">'; template = template.replace(/\\{\\{image_thumb\\}\\}/g, url); console.log(template); 

as a result I'm getting this:

http://s7d3.scene7.com/is/image/LuxotticaRetail/8053672035704_shad_fr?$jpegdefault{{image_thumb}}wid=45

As you can see the value that should have been replaced is in the middle of the string: {{image_thumb}} .

Do you know some way I could do to make this replace "ignore" the $ and keep the url as it should be?

I tried to use encodeURIComponent() but it changes other values of the url I don't want to be changed..

Any ideas?

Thanks for the help, guys.

I found a simple and easy solution:

template = template.replace(/\{\{image_thumb\}\}/g, function(){ return url });

This way the url is kept and the replace works like a charm

Syntax : RegExp['$&']

Description : The lastMatch property is static, it is not a property of an individual regular expression object. Instead, you always use it as RegExp.lastMatch or RegExp['$&'].

So please not that you have $& in your string and you use it in replace function that use regex expresions :

template = template.replace(/\{\{image_thumb\}\}/g, url);

So the $& in your string will be translated to lastMatch property that will print {{image_thumb}} instead of $& , That why you get :

<img class="thumb-img" src="http://s7d3.scene7.com/is/image/LuxotticaRetail/8053672035704_shad_fr?$jpegdefault{{image_thumb}}wid=45">

Simple example :

var url = "http://s7d3.scene7.com/is/image/LuxotticaRetail/8053672035704_shad_fr?$jpegdefault$&wid=45"
var template = '<img class="thumb-img" src="{{image_thumb}}">';

template = template.replace(/\{\{image_thumb\}\}/g, 'some $& text');

console.log(template);

//will return
<img class="thumb-img" src="some {{image_thumb}} text">

So you have to eliminate the expression $& from your url .

Source

Hope this helps.

要使replace函数忽略$,请先将其删除。

url = url.replace(/\$//g);

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