1

I wrote following function in order to parse available image sizes inside srcset attribute for each img element and return it as array. Everything works as expected when the debug mode is on, but once I disable the debug mode, the app would crash and throw following error:

Error: invalid regular expression invalid group specifier name

export function srcsetParser(htmlString) {

  let result = [];
  let images = htmlString.match(/<img\s+[^>]*srcset="([^"]*)"[^>]*>/g); // Finding img tags inside html string

  images && images.forEach(image => {
    let srcsets = image.match(/(?<=srcset=").+?(?=\")/g); //Select srcset value

    var urls = srcsets[0].split(", ");
    urls.forEach(url => {
      let temp = url.split(" ");
      result.push(temp[0]);
    });
  });
  return result;
}

Any idea what's wrong with the regex and why is it so only when debug mode is off ?

Thanks

1 Answers1

1

Update

The browser support isn’t great, but JavaScript now allows lookbehinds. The old answer is left below.


JavaScript regex doesn’t support lookbehinds. You can do it another way:

  images && images.forEach(image => {
    let srcsets = image.match(/srcset="(.+?)(?=\")/); //Select srcset value

    var urls = srcsets[1].split(", ");
    urls.forEach(url => {
      let temp = url.split(" ");
      result.push(temp[0]);
    });
  });
Anonymous
  • 11,748
  • 6
  • 35
  • 57
  • but `/srcset="(.+?)(?=\")/g` would include `srcset=`, is there a way to avoid that ? – Ehsan Ahmadizadeh Jul 23 '18 at 09:34
  • @EhsanAhmadizadeh I also changed `srcsets[0]` to `srcsets[1]`. `srcset=` should not be included. – Anonymous Jul 23 '18 at 11:40
  • But `srcsets[1]` is undefined for me! – Ehsan Ahmadizadeh Jul 23 '18 at 16:19
  • @EhsanAhmadizadeh Sorry, you have to also remove the `g` flag. Updated. – Anonymous Jul 23 '18 at 17:57
  • That did it. Thanks but why does it return two results instead of one ? There's no way with regex to just extract the text after `srcset="` till the next occurrence of `"` ? – Ehsan Ahmadizadeh Jul 25 '18 at 12:28
  • @EhsanAhmadizadeh Great. Glad I could help. It returns two results because it uses a capture group, which you can look up if you’re curious. There‘s no way to do it without that using JavaScript regex. Other languages can do it. – Anonymous Jul 25 '18 at 12:45
  • As mentioned in https://stackoverflow.com/a/50434875, support for lookbehinds was added to the ECMAScript specification in early 2018. Supported in Node.js v9 and Chrome 62, but not in Firefox and Edge. – Christian Schmidt Jan 18 '19 at 08:11