I'm trying to replace plain text for images using jQuery. The text is always between brackets, like so: {x} The problem however, is that there are always multiple bracketed letters that I want to turn into images. So {1}{w}{w} should become <img src="1.png"><img src="w.png"><img src="w.png">
So tl;dr: I need a way to turn this:
<div class="manacost">{1}{w}{w}</div>
Into this:
<div class="manacost"><img src="1.png'><img src="w.png"><img src="w.png"></div>
Thanks in advance.
asked Mar 22, 2014 at 9:49
Jefferson
9913 gold badges16 silver badges35 bronze badges
-
1I think your life will be easier if you check a templating engine (like mustache or handlebar)Irvin Dominin– Irvin Dominin2014年03月22日 10:21:56 +00:00Commented Mar 22, 2014 at 10:21
2 Answers 2
Use the replace method:
"{1}{w}{w}".replace(/\{([0-z]+)\}/g, "<img src='1ドル.png'>");
Update: In case you have multiple .manacost containers, try something like:
$('.manacost').html(function (index, text) {
this.innerHTML = text.replace(/\{([0-z]+)\}/g, "<img src='1ドル.png'>")
});
answered Mar 22, 2014 at 10:28
tewathia
7,3383 gold badges26 silver badges28 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Jefferson
I like this snippet because of it's simplicity. However, what if I had multiple instances of .manacost? You can see what I mean here: magicunited.microdesign.nl/product-category/BNG
Jefferson
I've chosen your answer as the correct one because of the shorter, more semantic code. Plus it respects the different instances of .manacost, leaving me with more room to adjust my css. Thank you very much for your help!
var content = $('.manacost').text();
var values = [], re = /{([^}]+)}/g, text;
while(text = re.exec(content)) {
values.push(text[1]);
}
$('.manacost').text('');
$.each( values, function( k, v ) {
// I don't know where you want to put
$('.manacost').append('<img src"'+v+'.png" alt="'+k+'"/>');
});
tewathia
7,3383 gold badges26 silver badges28 bronze badges
1 Comment
Jefferson
Brilliant, John. Absolutely brilliant. Thank you very much, sir!
default