[英]How to unescape amp; in JavaScript
Say I have this string java&script
, how can I convert this to java&script
? 说我有这个字符串
java&script
,如何将其转换为java&script
?
In the console of Google Chrome this doesn't work 在Google Chrome的控制台中,此功能无效
var str="java&script";
var str_esc=escape(str);
var str_unc = unescape(str_esc)
console.log(str_esc)
console.log(str_unc)
but this seems to work just fine 但这似乎很好
<!DOCTYPE html>
<html>
<body>
<script>
var str="java&script";
var str_esc=escape(str);
document.write(str_esc + "<br>")
document.write(unescape(str_esc))
</script>
</body>
</html>
Thank you for your help 谢谢您的帮助
You could decode the entity with a function that drops the string into a textarea, and then pulls the value from that, like so: 您可以使用将字符串放入文本区域的函数解码该实体,然后从中提取值,如下所示:
function htmlEntityDecode(str){ var txt = document.createElement('textarea'); txt.innerHTML = str; return txt.value; } var str = htmlEntityDecode("java&script"); console.log( str );
Or even simpler, if it really is just that one case, why not just use a simple .replace()
method on it? 甚至更简单,如果真的只是这种情况,为什么不对它使用简单的
.replace()
方法呢?
var str = 'java&script'; str = str.replace('&', '&'); console.log( str );
But if you have more than one instance, you would need to have a global replace : 但是,如果您有多个实例,则需要进行全局替换 :
var str = 'java & script and script & java'; str = str.replace(/&/g, '&'); console.log( str );
A simple solution to convert from an input string of say "java&script"
to "java&script"
can be achieved via the regular expression &
通过正则表达式
&
可以实现一种简单的解决方案,可以将输入的说"java&script"
为"java&script"
&
passed to the the string#replace
method : 传递给
string#replace
方法 :
var inputStr="java&script&jj"; /* match any occourance of & in the string and replace with &. Use the gi to cause replacement to happen irrespective of case (i) and globally across all occurances of & in the string (g). */ var unescapedStr = inputStr.replace(/&/gi, '&'); console.log(unescapedStr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.