简体   繁体   English

如何对放大器进行转义; 在JavaScript中

[英]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&amp;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&amp;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&amp;script'; str = str.replace('&amp;', '&'); console.log( str ); 

But if you have more than one instance, you would need to have a global replace : 但是,如果您有多个实例,则需要进行全局替换

 var str = 'java &amp; script and script &amp; java'; str = str.replace(/&amp;/g, '&'); console.log( str ); 

A simple solution to convert from an input string of say "java&amp;script" to "java&script" can be achieved via the regular expression &amp; 通过正则表达式&amp;可以实现一种简单的解决方案,可以将输入的说"java&amp;script""java&script" &amp; passed to the the string#replace method : 传递给string#replace方法

 var inputStr="java&amp;script&amp;jj"; /* match any occourance of &amp; in the string and replace with &. Use the gi to cause replacement to happen irrespective of case (i) and globally across all occurances of &amp; in the string (g). */ var unescapedStr = inputStr.replace(/&amp;/gi, '&'); console.log(unescapedStr); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM