Skip to content Skip to sidebar Skip to footer

Replacing Word(s) With Image Using Javascript/jquery

I have this: $('.forum-threadview-post-text:contains(':P')').html(':P').replaceWith(''); It is supposed to take any

Solution 1:

Try

var tImg = "<img src='http://website.com/images/emotes/tongue.png' />";
$(".forum-threadview-post-text:contains(':P')").html(function (_, html) {
     return html.replace(/:P/g , tImg )
});

Demo

Reason why yours doesn't work as expected is because you are replacing the matched element(s) with the image, not the specific content of it. You can use .html( function(index, oldhtml) ) to get the html of each element and replace it.

Or:

$(".forum-threadview-post-text:contains(':P')").contents().each(function () {
    if(this.nodeType === 3 && /:P/g.test(this.nodeValue)) {
       $(this).parent().html(this.nodeValue.replace(/:P/g,"<img src='http://placehold.it/10x10' />"));
    }
});

Solution 2:

I think it is best to not assume that the text will be an immediate child of the passed-in selector. I also see it as a bit chancy to assume that the text you are searching for cannot appear inside a descendant HTML tag. All other answers given so far have issues in at least one of these areas.

Furthermore, it is even better to make the code reusable. The below easily reusable functions will do exactly what you need, won't be messed up by stray HTML tag attributes, and work!

functiondescendantContents($el, textToFind) { // this could be made a jQuery pluginvar result = $el
      .find(':not(script)')
      .contents()
      .filter(function () {
         returnthis.nodeType === 3 && $(this).text().indexOf(textToFind) !== -1;
      });
   return result;
}

functionreplaceText(scopeSelector, textToFind, replacementHtml) {
   descendantContents($(scopeSelector), textToFind)
      .each(function () {
         var element = $(this);
         var parts = element.text().split(textToFind);
         element.before(document.createTextNode(parts[0]));
         for (var i = 1, l = parts.length; i < l; i += 1) {
            element.before(replacementHtml);
            element.before(document.createTextNode(parts[i]));
         }
         element.remove();
      });
};

These functions have been tested in Firefox 25.0.1, Chrome 30.0.1599.101 m, and 10.0.9200.16721 using jQuery 1.6.1 (I know, that's an old version, but that should make you feel better, not worse).

For anyone wishing to do better, try your code against this HTML:

<div><div>will this <spantitle="alt:Private">really</span> work :P</div></div>

Post a Comment for "Replacing Word(s) With Image Using Javascript/jquery"