0

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
1
  • 1
    I think your life will be easier if you check a templating engine (like mustache or handlebar) Commented Mar 22, 2014 at 10:21

2 Answers 2

2

Use the replace method:

"{1}{w}{w}".replace(/\{([0-z]+)\}/g, "<img src='1ドル.png'>");

DEMO

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'>")
});

DEMO

answered Mar 22, 2014 at 10:28
Sign up to request clarification or add additional context in comments.

2 Comments

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
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!
2
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
answered Mar 22, 2014 at 10:19

1 Comment

Brilliant, John. Absolutely brilliant. Thank you very much, sir!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.