1

i want to replace all the src attribute inside a string of HTML adding a '?a' at the end of the url to fix a caching issue that i'm having.

So far i got this:

str.replace(/src=".*?"/gi, "src");

But i have no idea how to do the 2nd parameter to get what is matched and add the '?a' at the end.

Example:

<img src="mysite.com/logo.png" /> should become

<img src="mysite.com/logo.png?a" />

Thank you in advance, Daniel!

2
  • 3
    .replace(/src="(.*?)"/gi, 'src="$1?a"'); Commented Aug 25, 2015 at 9:52
  • mdn doc Commented Aug 25, 2015 at 9:55

2 Answers 2

3

The first problem is that you are matching the entire src attribute instead of what's within the src attribute.

The second problem is that you aren't putting the match into your replacement.

This would be the correct regex:

str.replace(/src="(.*?)"/gi, 'src="$1?a"')/;

Adding brackets around the match .*? makes sure you match just that part instead of the whole regex, adding $1 into the second parameter makes sure you put the match back into the replacement.

You also have to re-enter src="" into the replacement, because the whole regex match will be replaced.

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

2 Comments

thank you very much for the answer, it works exactly as i expected to!
No problem, don't forget to mark the question as answered!
0

You can use this /src="(.*?)"/gi regex to find and replace the content. enter image description here

Comments

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.