开发者

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&开发者_运维知识库amp;#45;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 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&#45;of-5").text()

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜