在JavaScript中取消撇号

在JavaScript中取消撇号

本文介绍了在JavaScript中取消撇号(')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在JavaScript中取消转义HTML转义的撇号('),但以下内容似乎不适用于devtools console line:

  unescape('''); 

输出简单:

  &安培;#39; 

它在Underscore的unescape中不起作用:

  _。unescape(''')

我做错了什么?

解决方案

unescape 与HTML字符实体无关。这是一个旧的,不推荐的功能,用于解码使用 escape 编码的文本,这是一种旧的,不推荐使用的函数,用于在现代世界中不太有用的方式对文本进行编码。 : - )



如果您需要将该HTML转换为纯文本,最简单的方法是通过元素:

  var div = document.createElement('div'); 
div.innerHTML =';
alert(div.firstChild.nodeValue);

|



请注意,以上依赖于HTML文本中没有定义元素的事实,因此它知道正是一个 div 的子节点,它是一个文本节点。 >

对于更复杂的用例,您可以使用 div.innerText (如果有)或 div.textContent

  var div = document.createElement('div'); 
div.innerHTML =';
alert(div.innerText || div.textContent ||);

|


I'm trying to unescape a HTML-escaped apostrophe ("'") in JavaScript, but the following doesn't seem to work on a devtools console line:

unescape(''');

The output is simply:

"'"

It doesn't work in Underscore's unescape either:

_.unescape(''')

What am I doing wrong?

解决方案

unescape has nothing to do with HTML character entities. It's an old, deprecated function for decoding text encoded with escape, which is an old, deprecated function for encoding text in a way that is unlikely to be useful in the modern world. :-)

If you need to turn that HTML into plain text, the easiest way is via an element:

var div = document.createElement('div');
div.innerHTML = "'";
alert(div.firstChild.nodeValue);

Live Example | Live Source

Note that the above relies on the fact that there are no elements defined in your HTML text, so it knows there is exactly one child node of div, which is a text node.

For more complicated use cases, you might use div.innerText (if it has one) or div.textContent:

var div = document.createElement('div');
div.innerHTML = "'";
alert(div.innerText || div.textContent || "");

Live Example | Live Source

这篇关于在JavaScript中取消撇号(')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 21:23