Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 879
amber Avatar asked May 27 '11 17:05

amber


People also ask

How to convert HTML content to plain text in JavaScript?

The easiest way would be to strip all the HTML tags using the replace() method of JavaScript. It finds all tags enclosed in angle brackets and replaces them with a space. var text = html.

How do you encode an HTML entity?

The htmlentities() function converts characters to HTML entities. Tip: To convert HTML entities back to characters, use the html_entity_decode() function. Tip: Use the get_html_translation_table() function to return the translation table used by htmlentities().

Which method converts the input into numeric value in JavaScript?

The Number() method converts a value to a number. If the value cannot be converted, NaN is returned.

What is HTML &GT?

&gt; and &lt; is a character entity reference for the > and < character in HTML. It is not possible to use the less than (<) or greater than (>) signs in your file, because the browser will mix them with tags. for these difficulties you can use entity names( &gt; ) and entity numbers( &#60; ).


3 Answers

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&#45;of-5");
like image 59
Jeff Avatar answered Nov 02 '22 23:11

Jeff


No need to use jQuery for this simple task:

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

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

like image 24
krcko Avatar answered Nov 03 '22 01:11

krcko


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

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

like image 25
Dustin Laine Avatar answered Nov 03 '22 01:11

Dustin Laine