当前位置: 动力学知识库 > 问答 > 编程问答 >

html - 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);

网友答案:

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.

网友答案:

To make the replace function ignore the $, remove it first.

url = url.replace(/\$//g);
分享给朋友:
您可能感兴趣的文章:
随机阅读: