Mladen
Mladen

Reputation: 31

How to replace character with image using jQuery?

How to replace ALL * characters in some list?

Example:

<div class="nav">
        <ul>
            <li><a href="#">Hotels *****</a></li>
            <li><a href="#">Hotels ****</a></li>
            <li><a href="#">Hotels ***</a></li>
            <li><a href="#">Some other menu</a></li>
        </ul>
</div>

jQuery example:

$().ready(function () {
    if ($('.logo')[0].offsetWidth == 295) {
        $('.nav ul li a span').each(function () {
            string = $(this).text();
            $(this).html('<img src="img/star.png" alt="' + string + '" />');
        });
    }
});

I want to change ALL the stars, not just one (with this code, all works like it should, except it changes all stars with one image). it shuld be how many star char's, that many images.

The goal is to change it like this:

some text ***** 

with

some text <img src="img/star.png" alt="star" /><img src="img/star.png" alt="' + string + '" /><img src="img/star.png" alt="' + string + '" /><img src="img/star.png" alt="' + string + '" /><img src="img/star.png" alt="' + string + '" />

Upvotes: 3

Views: 4181

Answers (4)

user113716
user113716

Reputation: 322502

You can do this very cleanly by just passing a function to the html()[docs] method.

$('.nav ul li a').html(function(i,html) {
    return html.replace(/\*/g, '<img src="http://dummyimage.com/30x30/f00/fff.png&text=*" alt="' + html + '" />');
});

Example: http://jsfiddle.net/vrqgv/

Upvotes: 1

Gus
Gus

Reputation: 7349

Once you have your string:

some text ***** 

you can use split() and join() to replace the stars with the images:

var original = 'some text *****' ;
var withImages = original.split('*').join('<img src="img/star.png" alt="star" />');

Split creates an array with each element separated by the string passed in, and join returns an array to a string, inserting the passed string between each element.

Upvotes: 0

a&#39;r
a&#39;r

Reputation: 36999

Iterate over the required elements and use a regex to change the '*' to the <img> elements. You will need a /g flag on the regex to change all of them in the string.

$('...').each(function() {
    var $this = $(this),
        html = $this.html();

    html = html.replace(/\*/g, '<img href="...">');
    $this.html(html);
});

Upvotes: 2

Mrchief
Mrchief

Reputation: 76218

Your selector is not in sync with your markup:

$('.nav ul li a span') -> there is no span in your lis

Fixing that selector, here's the code that would do the trick:

$('.nav ul li a').each(function() {
    var txt = $(this).text();
    var img = '<img src="img/star.png" alt="' + txt + '" />'
    var html = txt.replace(/\*/g, img);  // replace every star with an image tag
    $(this).html(html);
});

Here's demo: http://jsfiddle.net/mrchief/kycae/

Upvotes: 1

Related Questions