Skip to content
Advertisement

How to get the start and last index of a string match

I am trying to get the last and first index of a string match. For example:

JavaScript

What I would like to do is get the first index and last index of the match. example I have attempted:

JavaScript

wanted output

JavaScript

I’m unsure if this is the correct way, it doesnt seem to work for me.

Thanks.

Advertisement

Answer

You are almost there, I’ve made some changes:

  • The regex pattern needs to have .*? to match lazily up to the next src attribute or the > closing tag.
  • The method used is String.replace, because it allows to have the full matched image img, and also to have the src matched group () in the second argument.
  • Using string interpolation `` (backticks) eases the concatenion of the resulting string.

Look the final function:

JavaScript
JavaScript
JavaScript

You can play with the regex pattern here:

Advertisement