jquerycssimage-replacement

Replace '&' with an image using jQuery/CSS?


Is there a way I can change the basic text version of '&' and replace it with an image? I was thinking can we do it in jQuery? I don't want to use php for this.

Or is there a way to target it using css?

Thanks.


Solution

  • Yes, you could do it like this (asuming you want to replace inside #container element):

    var origText = $("#container").text();
    $("#container").text(origText.replace(/&/g, "__img_mark__"));
    var intermediateHtml = $("#container").html();
    $("#container").html(intermediateHtml.replace(/__img_mark__/g, '<img src="ampersand.gif" />'));
    

    We're doing it in 2 steps because we don't want ampersands in the html code to be replaced

    Hope this helps. Cheers