Hamzar
Hamzar

Reputation: 83

javascript regex to replace all img src with data-src

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 ?

Upvotes: 1

Views: 962

Answers (3)

nu11p01n73R
nu11p01n73R

Reputation: 26667

Positive look aheads would be helpfull

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

Regex Demo

Upvotes: 0

user663031
user663031

Reputation:

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 = '';
}

Upvotes: 4

Soronbe
Soronbe

Reputation: 926

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

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

would ne more correct.

Upvotes: 0

Related Questions