amber
amber

Reputation: 1137

How do I convert an HTML Entity Number into a character using plain JavaScript or jQuery?

I'm looking for a way to convert HTML entity numbers into a character using plain JavaScript or jQuery.

For example, I have a string that looks like this (Thank you, jQuery! Punk.)

Range1-of-5

And what I need is:

Range1-of-5

I've found String.fromCharCode() where I can get the character with just the decimal value, but I'd like to see if anyone else has a solution before I possibly reinvent the wheel. :)

Upvotes: 5

Views: 3980

Answers (3)

krcko
krcko

Reputation: 2834

No need to use jQuery for this simple task:

'Range1-of-5'.replace(/&#(\d+);/g, function(match, number){ return String.fromCharCode(number); })

The same principle can be applied to &#xHHHH; and &name; entities.

Upvotes: 5

Jeff
Jeff

Reputation: 21892

The jQuery way looks nicer, but here's a pure JS version if you're interested:

function decode(encodedString) {
    var tmpElement = document.createElement('span');
    tmpElement.innerHTML = encodedString;
    return tmpElement.innerHTML;
}

decode("Range1-of-5");

Upvotes: 5

Dustin Laine
Dustin Laine

Reputation: 38513

$("<div/>").html("Range1&#45;of-5").text()

http://jsfiddle.net/durilai/tkwEh/

Upvotes: 4

Related Questions