Reputation: 4696
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?
Upvotes: 0
Views: 53
Reputation: 4696
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
Upvotes: 2
Reputation: 67525
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
.
Hope this helps.
Upvotes: 1
Reputation: 121
To make the replace function ignore the $, remove it first.
url = url.replace(/\$//g);
Upvotes: 0