1

i want to replace all img src with data-src and this is my pattern :

(<img.*?)src

but this one is also matching data-src so when i use in on a loop it ouput something like that

<img data-data-data-data-data-data-data-data-data-data-data-data-data-data-src="..">

any help ?

2
  • 1
    Why would you be running this over and over in a loop? Commented Dec 7, 2015 at 6:19
  • Use the /g flag, don't run the same pattern in a loop. Commented Dec 7, 2015 at 6:27

3 Answers 3

4

Don't use regexp for this. Just

var images = document.querySelectorAll('img');
for (var i = 0; i < images.length; i++) {
  var img = images[i];
  img.dataset.src = img.src;
  img.src = '';
}
Sign up to request clarification or add additional context in comments.

Comments

0

(<img.*?)[^-]src will work, but regexes try to get the longest match, so

(<img[^>])[^->]src

would ne more correct.

Comments

0

Positive look aheads would be helpfull

<img(?![^>\n]*data-src)[^>\n]*src

Regex Demo

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.