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 Answer 1

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]);
    });
  });
Sign up to request clarification or add additional context in comments.

7 Comments

but /srcset="(.+?)(?=\")/g would include srcset=, is there a way to avoid that ?
@EhsanAhmadizadeh I also changed srcsets[0] to srcsets[1]. srcset= should not be included.
But srcsets[1] is undefined for me!
@EhsanAhmadizadeh Sorry, you have to also remove the g flag. Updated.
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 " ?
|

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.