I have multiple pieces of text that need replacement on a page to corresponding images.
I have this code:
$('.icon-box-1').each(function() {
var text = $(this).text();
$(this).html(text.replace('1', '<img src="1.png" alt="" />'));
$(this).html(text.replace('2', '<img src="2.png" alt="" />'));
$(this).html(text.replace('3', '<img src="3.png" alt="" />'));
});
Unfortunately it only replaces 1 of the 3. How do i get it to update all 3?
Thanks
CodePudding user response:
You want to update text
with each replacement, then call .html()
with text
, which then has all of the replacements:
$('.icon-box-1').each(function() {
var text = $(this).text()
.replace('1', '<img src="1.png" alt="" />')
.replace('2', '<img src="2.png" alt="" />')
.replace('3', '<img src="3.png" alt="" />');
$(this).html(text);
});
CodePudding user response:
Check this fiddle: https://jsfiddle.net/qp78rdzo/
$('.icon-box-1').each(function() {
var text = $(this).text();
text = text.replace('1', '<img src="1.png" alt="">');
text = text.replace('2', '<img src="2.png" alt="">');
text = text.replace('3', '<img src="3.png" alt="">');
$(this).html(text);
});
CodePudding user response:
Assuming that the text to be replaced is always an integer and always matches the filename of the image, then you can make the code a one-liner using an arrow function and a regular expression:
$('.icon-box-1').html((_, h) => h.replace(/(\d)/g, '<img src="$1.png" alt="$1" />'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div >This is 1</div>
<div >This is 2</div>
<div >This is 3</div>
<div >This is 1 and 2</div>
<div >This is 2 and 3</div>
<div >This is 3 and 1</div>