Spufferoo
Spufferoo

Reputation: 127

Jquery conditional regex return output

Is it possible to use regex and jQuery to return conditional output, I would like to replace numbers surrounded by square brackets for images:

[1] would become <span><img src="1.png"></span>

where I have [11] it would replace it as

<span><img src="1.png"><img src="1.png"></span>

where I have [1e1] it would replace it as

<span><img src="1.png"><img src="e.png"><img src="1.png"></span>

However if it is only text it will leave as is regardless of length

[qu] would become <span><img src="qu.png"></span>

This is the code I have so far:

$('p').each(function() {
    var txt = $(this).text();               
    var html = txt.replace(/\[(.*?)\]/g, function($1){

        if($1.length<=3) {
            return $1.replace(/\[(.*?)\]/g,'<span class=\'rehMark\'><img src="img/$1.png" alt="$1" /></span>')
        }else{

// this is the bit I would like help with!
// and how to deal with text rather than numbers

            return '<span class=\'lngRehMark\'>'

            for (i=0; i<$1.length; i++ )
            {
                return '<img src="img/' + $1 + '.png" alt="' + $1.length + '" /></span>'
            }
            return '</span'>'
        }
    });

    $(this).html(html);
});

Upvotes: 0

Views: 403

Answers (1)

Miroslav Bajtoš
Miroslav Bajtoš

Reputation: 10785

You can use split, map and join to convert [12] to an array of <img> elements.

Also note that the first parameter of replace callback contains full matched string (e.g. [11]), not the first matched group (e.g. 11).

$('p').each(function() {
    var txt = $(this).text();               
    var html = txt.replace(/\[([^\]]*)\]/g, function(match, chars){
        var images;
        if (chars.match(/^[^0-9]*$/))
            images = '<img src="img/' + chars + '.png" />';
        else
            images = $(chars.split(''))
              .map(function() { return '<img src="img/' + this + '.png" />'; })
              .get().join('');
        return '<span class=\'lngRehMark\'>' + images + '</span>';
    });

    $(this).html(html);
});

Upvotes: 1

Related Questions