I am trying to get the last and first index of a string match. For example:
JavaScript
x
2
1
var text = 'I am a string and this is an image <img src="image.jpeg">';
2
What I would like to do is get the first index and last index of the match. example I have attempted:
JavaScript
1
14
14
1
<script>
2
function getLightBox(text) {
3
var result = str.match(/<img src="(.*?)>/g).map(function(val){
4
var res = val.replace(/</?img src =">/g,'').replace(/?>/g,'');
5
var tag1 = text.firstIndexOf((/<img src="(.*?)>/g));
6
var tag2 = text.lastIndexOf((/<img src="(.*?)>/g));
7
var anchor1 = '<a href="images/' + res +'" data-lightbox="Christmas">';
8
var anchor2 = '</a>'
9
var newString = text.substring(0,tag1) + anchor1 + '<img src="' + res + '">' + anchor2 + text.substring(tag2,text.length);
10
return newString;
11
12
});
13
</script>
14
wanted output
JavaScript
1
2
1
I am a string and this is an image <a href="images/image.jpeg" data-lightbox="Christmas"><img=src"image.jpeg"></a>
2
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 nextsrc
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
1
8
1
function getLightBox(text = '') {
2
return text.replace(/<img.*?src="([^"]+)".*?>/g, (img, src) => {
3
return `<a href="images/${src}" data-lightbox="Christmas">${img}</a>`;
4
});
5
}
6
7
const element = document.getElementById('myElement');
8
element.innerHTML = getLightBox(element.innerHTML);
JavaScript
1
9
1
img {
2
padding: 0 10px;
3
background-color: yellow;
4
}
5
6
a {
7
padding: 0 20px;
8
background-color: red;
9
}
JavaScript
1
4
1
<div id="myElement">
2
I am a string and this is an image:
3
<img id="foo" src="image.jpeg" alt="bar">
4
</div>
You can play with the regex pattern here: