Skip to content Skip to sidebar Skip to footer

Value &# To Unicode Convert

I have lots of characters in the form ¶ which I would like to display as unicode characters in my text editor. This ought to convert them: var newtext = doctext.replace(

Solution 1:

The replacement part should be an anonymous function instead of an expression:

var newtext = doctext.replace(
    /&#(\d+);/g, 
    function($0, $1) {
        returnString.fromCharCode(parseInt($1, 10));
    }
);

Solution 2:

The replace method is not foolproof, if you use full HTML (i.e. don't control what the input is). For example, the method submitted by Jack (and obviously the idea in the original post as well) works excellently if your entities are all decimal, but doesn't work for hex A, and even less for named entities like ".

For this, there is another trick you can do: create an element, set its innerHTML to the source, then read out its text value. Basically, browsers know what to do with entities, so we delegate. :) In jQuery it is easy:

$('<div/>').html('&amp;').text()
// => "&"

With plain JS it gets a bit more verbose:

var el = document.createElement();
el.innerHTML = '&amp;';
el.textContent// => "&"

Post a Comment for "Value &# To Unicode Convert"