我如何编码和解码HTML实体使用JavaScript或JQuery?
var varTitle = "Chris' corner";
我希望它是:
var varTitle = "Chris' corner";
我如何编码和解码HTML实体使用JavaScript或JQuery?
var varTitle = "Chris' corner";
我希望它是:
var varTitle = "Chris' corner";
当前回答
你可以尝试这样做:
var Title = $('<textarea />').html("Chris'角”)。text (); console.log(标题); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本>
J.S.小提琴。
更具互动性的版本:
$('form').submit(function() { var theString = $('#string').val(); var varTitle = $('<textarea />').html(theString).text(); $('#output').text(varTitle); return false; }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action="#" method="post"> <fieldset> <label for="string">Enter a html-encoded string to decode</label> <input type="text" name="string" id="string" /> </fieldset> <fieldset> <input type="submit" value="decode" /> </fieldset> </form> <div id="output"></div>
J.S.小提琴。
其他回答
@William Lahti的回答有一个更实用的方法:
var entities = {
'amp': '&',
'apos': '\'',
'#x27': '\'',
'#x2F': '/',
'#39': '\'',
'#47': '/',
'lt': '<',
'gt': '>',
'nbsp': ' ',
'quot': '"'
}
function decodeHTMLEntities (text) {
return text.replace(/&([^;]+);/gm, function (match, entity) {
return entities[entity] || match
})
}
要做到这一点,在纯javascript没有jquery或预定义一切,你可以循环编码的html字符串通过元素innerHTML和innerText(/textContent)属性的每解码步骤,这是必需的:
<html>
<head>
<title>For every decode step, cycle through innerHTML and innerText </title>
<script>
function decode(str) {
var d = document.createElement("div");
d.innerHTML = str;
return typeof d.innerText !== 'undefined' ? d.innerText : d.textContent;
}
</script>
</head>
<body>
<script>
var encodedString = "<p>name</p><p><span style=\"font-size:xx-small;\">ajde</span></p><p><em>da</em></p>";
</script>
<input type=button onclick="document.body.innerHTML=decode(encodedString)"/>
</body>
</html>
因为@Robert K和@mattcasey都有很好的代码,我想在这里贡献一个CoffeeScript版本,以防将来有人会使用它:
String::unescape = (strict = false) ->
###
# Take escaped text, and return the unescaped version
#
# @param string str | String to be used
# @param bool strict | Stict mode will remove all HTML
#
# Test it here:
# https://jsfiddle.net/tigerhawkvok/t9pn1dn5/
#
# Code: https://gist.github.com/tigerhawkvok/285b8631ed6ebef4446d
###
# Create a dummy element
element = document.createElement("div")
decodeHTMLEntities = (str) ->
if str? and typeof str is "string"
unless strict is true
# escape HTML tags
str = escape(str).replace(/%26/g,'&').replace(/%23/g,'#').replace(/%3B/g,';')
else
str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '')
str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '')
element.innerHTML = str
if element.innerText
# Do we support innerText?
str = element.innerText
element.innerText = ""
else
# Firefox
str = element.textContent
element.textContent = ""
unescape(str)
# Remove encoded or double-encoded tags
fixHtmlEncodings = (string) ->
string = string.replace(/\&#/mg, '&#') # The rest, for double-encodings
string = string.replace(/\"/mg, '"')
string = string.replace(/\"e;/mg, '"')
string = string.replace(/\_/mg, '_')
string = string.replace(/\'/mg, "'")
string = string.replace(/\"/mg, '"')
string = string.replace(/\>/mg, '>')
string = string.replace(/\</mg, '<')
string
# Run it
tmp = fixHtmlEncodings(this)
decodeHTMLEntities(tmp)
请参阅https://jsfiddle.net/tigerhawkvok/t9pn1dn5/7/或https://gist.github.com/tigerhawkvok/285b8631ed6ebef4446d(包括编译过的JS,可能比这个答案更新了)
我知道我有点晚了,但我认为我可以提供以下片段作为我如何使用jQuery解码HTML实体的示例:
var varTitleE = "Chris' corner";
var varTitleD = $("<div/>").html(varTitleE).text();
console.log(varTitleE + " vs. " + varTitleD);
不要忘记启动检查器/firebug以查看控制台结果——或者简单地将console.log(…)替换为/alert(…)
也就是说,以下是我的控制台通过谷歌Chrome检查器读取的内容:
Chris' corner vs. Chris' corner
我不建议使用jQuery代码作为答案。虽然它不会将要解码的字符串插入到页面中,但它确实会创建脚本和HTML元素等内容。这代码比我们需要的多。相反,我建议使用更安全、更优化的函数。
var decodeEntities = (function() {
// this prevents any overhead from creating the object each time
var element = document.createElement('div');
function decodeHTMLEntities (str) {
if(str && typeof str === 'string') {
// strip script/html tags
str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
element.innerHTML = str;
str = element.textContent;
element.textContent = '';
}
return str;
}
return decodeHTMLEntities;
})();
http://jsfiddle.net/LYteC/4/
要使用这个函数,只需调用decodeEntities(“&”),它将使用与jQuery版本相同的底层技术——但是没有jQuery的开销,并且在清除输入中的HTML标记之后。请参阅Mike Samuel关于如何过滤HTML标记的公认答案的评论。
这个函数可以很容易地作为jQuery插件使用,只需在您的项目中添加以下行即可。
jQuery.decodeEntities = decodeEntities;