Density
Density

Reputation: 91

Replace text with img based off of text

I want to replace text with the an img using part of itself:

<li class='custom'>
 <legend>images:</legend>
 {[img.png][1desc][2desc]} {[img2.png][1desc2][2desc2]}
</li>

I want it to appear as this:

<li class='custom'>
 <legend>images:</legend>
 <img src="img.png" title="1desc - 2desc"/> <img src="img2.png" title="1desc2 - 2desc2"/>
</li>

Current code I am using(doesn't work):

<script>
function textToImg(theImg) {
  return theImg.replace(
           /\{\s*[\s*(.*?)\s*]\s*[\s*(.*?)\s*]\s*[\s*(.*?)\s*]\s*\}/gi,
           '<img src="$1" title="$2 - $3"/>'
         );
}

jQuery('li.custom').each(function() {

    current = jQuery(this);

    IMG = textToImg(current.html());

    current.html(IMG);

});
</script>

Upvotes: 1

Views: 41

Answers (1)

Mottie
Mottie

Reputation: 86403

It looks like the [ and ] in the regular expression are not being properly escaped. Try this (demo):

function textToImg(theImg) {
  return theImg.replace(
           /\{\s*\[\s*(.*?)\s*\]\s*\[\s*(.*?)\s*\]\s*\[\s*(.*?)\s*\]\s*\}/gi,
           '<img src="$1" title="$2 - $3"/>'
         );
}

Upvotes: 1

Related Questions