0

I can't figure out why my jquery replacement code wouldn't work.

I try to make the follow replacement:

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

I added '$var' to the position where I want to put a number, we can take '1' for now. So I need to replace $var for 1.

What I tried;

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

But nothing happens.

Thanks in advance!

Nick

1 Answer 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.)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for this zupa dupa fast answer! I will accept it when I can :)
Oh and also, the .replace() function returns the value but doesn't change the original string; I'll update the answer @Freshtea .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.