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. :)
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.
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().
The Number() method converts a value to a number. If the value cannot be converted, NaN is returned.
> and < 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( > ) and entity numbers( < ).
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");
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.
$("<div/>").html("Range1-of-5").text()
http://jsfiddle.net/durilai/tkwEh/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With