0

Hi i would like to capture everything between img src="...", however not sure why the code below is not working

var stringHtml = '<img src="content://media/external/images/media/21260"><img src="content://media/external/images/media/21260"><img src="content://media/external/images/media/21260">';
var srcArray = ['x.png', 'y.png', 'z.png']

var rgx = /<img src="([^"]+)"/g;
var match;

for (var a = 0; a < srcArray.length; a++) {
  match = rgx.exec(stringHtml);
  stringHtml = stringHtml.replace(match[1], srcArray[a]);
}

alert(stringHtml);
epascarello
  • 204,599
  • 20
  • 195
  • 236
moleeee
  • 37
  • 5
  • 1
    "not working" is not a good explaination about the problem. – epascarello Jun 17 '18 at 13:48
  • Please provide more detail about what error is occuring and what you are trying to achieve – e11i0t23 Jun 17 '18 at 13:50
  • debug and see what is happening: `match = rgx.exec(stringHtml); console.log(match, stringHtml)` – epascarello Jun 17 '18 at 13:51
  • basically im trying to capture everything in my img src="..." in stringHTML and replace that with elements in scrArray, however, when there are / and more than a number of characters it show as invalid java. – moleeee Jun 17 '18 at 13:52
  • What do you expect `alert(stringHTML)` to produce? What is it currently producing? If there is an error, provide the actual error message please, because "invalid java" doesn't mean anything. – James Jun 17 '18 at 13:55
  • don't you need `'` around your regex? i.e. `var rgx = '/ – Claies Jun 17 '18 at 13:57
  • the outcome should be - stringHtml = ''; – moleeee Jun 17 '18 at 13:57
  • @Claies thats still giving me an error – moleeee Jun 17 '18 at 13:58
  • giving you **what** error? multiple people have tried to say, post the error code ***in the question body***. That being said, I agree with @bambam – Claies Jun 17 '18 at 13:59

1 Answers1

3

Like answered so often, don't use regex to parse html. Instead, parse the string and easily and reliable get the src

var stringHtml = '<img src="content://media/external/images/media/21260"><img src="content://media/external/images/media/21260"><img src="content://media/external/images/media/21260">';

const parser = new DOMParser().parseFromString(stringHtml, 'text/html');

for (let img of parser.getElementsByTagName('img')) {
  console.log(img.src);
}
baao
  • 71,625
  • 17
  • 143
  • 203