Skip to content

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:

var text = 'I am a string and this is an image <img src="image.jpeg">';

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

        function getLightBox(text) {
                var result = str.match(/<img src="(.*?)>/g).map(function(val){
                var res = val.replace(/</?img src =">/g,'').replace(/?>/g,'');
                var tag1 = text.firstIndexOf((/<img src="(.*?)>/g));
                var tag2 = text.lastIndexOf((/<img src="(.*?)>/g));
                var anchor1 = '<a href="images/' + res +'" data-lightbox="Christmas">';
                var anchor2 = '</a>'
                var newString = text.substring(0,tag1) + anchor1 + '<img src="' + res + '">'  + anchor2 + text.substring(tag2,text.length);
                return newString;

wanted output

I am a string and this is an image <a href="images/image.jpeg" data-lightbox="Christmas"><img=src"image.jpeg"></a>

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



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:

function getLightBox(text = '') {
  return text.replace(/<img.*?src="([^"]+)".*?>/g, (img, src) => {
    return `<a href="images/${src}" data-lightbox="Christmas">${img}</a>`;
const element = document.getElementById('myElement');
element.innerHTML = getLightBox(element.innerHTML);
img {
  padding: 0 10px;
  background-color: yellow;
a {
  padding: 0 20px;
  background-color: red;
<div id="myElement">
  I am a string and this is an image:
  <img id="foo" src="image.jpeg" alt="bar">

You can play with the regex pattern here: