5

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. :)

1

3 Answers 3

5

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");
Sign up to request clarification or add additional context in comments.

1 Comment

Cool. Worked for me :)
5

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.

1 Comment

This worked but as I explore corner cases I'm concerned it's not going to scale well into different use cases. I did upvote it as it strikes me as very useful, just not as robust as I think I might need going above and beyond the initial use case above.
4
$("<div/>").html("Range1&#45;of-5").text()

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

1 Comment

This looks to be the simplest and most robust. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.