0

我不知道为什么我的 jquery 替换代码不起作用。

我尝试进行以下替换:

http://mysite.com/_thumbs/0000312/0312718/0312718_$varm.jpg

我在要输入数字的位置添加了“$var”,我们现在可以取“1”。所以我需要将 $var 替换为 1。

我尝试了什么;

 var img = $('img', this).attr('src'); // I grabs the image url like above.
 img.replace(/$var/, 1)

但什么也没有发生。

提前致谢!

缺口

4

1 回答 1

2

The dollar sign is a special character in regular expressions.

img.replace(/\$var/, "1");

Escaping the $ with a backslash will tell JavaScript that you want it to match a dollar sign. Otherwise, $ means "match the end of the search string".

edit — also note that if you want the updated string you'll need to save the return value from calling .replace():

img = img.replace(/\$var/, "1");

(You can of course save the replacement results in a different variable.)

于 2013-09-16T20:41:56.433 回答