Skip to content Skip to sidebar Skip to footer

Jquery Replacing Special Characters

I'm trying to replace all instances where an escaped register (®) symbol appears on a content managed website on page load. Basically, my problem is that this code does not work:

Solution 1:

This seems to work:

$(document.body).html($(document.body).html().replace(/&reg;|®/g, "<sup>&reg;</sup>"));

This also replaces more than one symbol in a given object which your original code did not.

FYI, you don't have to look in every element individually. You could just look in the HTML of the body and replace all there as long as you don't think this pattern would legitimately occur in an HTML attribute and as long as you are doing this before attaching any event handlers.

If you want to traverse each element individually, you can use this replace logic with your original code like this:

$("*").each(function() { 
    if($(this).children().length==0) { 
        $(this).html($(this).html().replace(/&reg;|®/g, '<sup>&reg;</sup>')); 
    } 
});

Here's a fiddle: http://jsfiddle.net/jfriend00/DqdwX/

Solution 2:

Put the ® character into your javascript regex:

$("*").each(function()
{ 
    if ( ! $(this).children().length )
    { 
        $(this).html(function(el, html)
        {
            return html.replace(/®/g, '<sup>&reg;</sup>'); 
        });
    } 
});

Here's the fiddle: http://jsfiddle.net/Lh9f6/


P.S. As mentioned by @jfriend00, if you know that you won't have this special character in any attributes (for example in alt), and you're doing this before binding any events to any of your elements, then you don't have to loop through it all. You could just do it once on the body, and it should replace all of them.

Solution 3:

You should check for instances of the ® character. If you're using a text editor that wont allow you to inline ®, you could use the JS escaped unicode equivalent:

'\u00ae'

Regex would help with this:

...replace(/\u00ae|&reg;/g, ...);

Solution 4:

It is possible, that the character is literal in the HTML source. Then the escape notation &reg; doesn't match. Use this:

...replace(newRegExp('(&reg;|\u00AE)', 'g'), '<sup>$1</sup>');

\u00AE is the Javascript-escaped notation for Unicode codepoint U+00AE, aka ®.

Post a Comment for "Jquery Replacing Special Characters"