3

I have this regex

 var reg = new RegExp('["\\>]{1}\\$([^"\\<\\> ]*)["\\<]{1}', 'g');

That I run on this string

'<span>$name</span><img src="$images[0].src"><img src="$images[1].src"><img src="$images[2].src">'

If I test it on sites like RegExr it works properly but if I test it in FireFox

var reg = new RegExp('["\\>]{1}\\$([^"\\<\\> ]*)["\\<]{1}', 'g');
var match = reg.exec('<span>$name</span><img src="$images[0].src"><img src="$images[1].src"><img src="$images[2].src">');
console.log(match);

It only matches ">$name<". How to have it catch all like on the site?

This is not a duplicate. i'm not working with query strings, beside it works online of the site.

Eric
  • 9,870
  • 14
  • 66
  • 102

3 Answers3

5

Regexp.prototype.exec() just returns the first occurrence of a match, you have to call it in a loop to get all the matches.

Simpler is to use String.prototype.match(), it returns an array of all the matches.

You only need to use exec() if you also need to get the capture groups.

var reg = new RegExp('[">]\\$[^"<> ]*["<]', 'g');
var str = '<span>$name</span><img src="$images[0].src"><img src="$images[1].src"><img src="$images[2].src">';
var match = str.match(reg);
console.log(match);
Barmar
  • 741,623
  • 53
  • 500
  • 612
4

The .exec() method return only the first occurrence, if you want to return all occurences use .match() :

var reg = new RegExp('[>"]\\$([^"<> ]*)["<]', 'gm');
var my_string = '<span>$name</span><img src="$images[0].src"><img src="$images[1].src"><img src="$images[2].src">';
var match = my_string.match(reg);

console.log(match);
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
3

You should convert HTML text to DOM and parse it.

var div = document.createElement('div');
div.innerHTML = '<span>$name</span><img src="$images[0].src"><img src="$images[1].src"><img src="$images[2].src">';
var result = [];
result.push(div.querySelector('span').innerText);
var src = Array.from(div.querySelectorAll('img')).map(img => img.getAttribute('src'));
result = result.concat(src);
console.log(result);

You can use string#match.

var reg = new RegExp('["\\>]{1}\\$([^"\\<\\> ]*)["\\<]{1}', 'g');
var match = '<span>$name</span><img src="$images[0].src"><img src="$images[1].src"><img src="$images[2].src">'.match(reg);
console.log(match);
Aarif Aslam
  • 1,077
  • 10
  • 15