测试特殊字符JavaScript

时间:2015-09-26 20:58:58

标签: javascript html

说我有这个HTML元素:

<td>&mdash;</td>

当浏览器解析时,&mdash;会转换为实际的em-dash,如下所示:

<td>—</td>

如何在不使用JavaScript代码中的其他字符的情况下测试&mdash;

console.log(elem.innerHTML == "&mdash;"); // false
console.log(elem.textContent == "&mdash;"); // false
console.log(elem.innerHTML == "—"); // true
console.log(elem.textContent == "—"); // true

3 个答案:

答案 0 :(得分:3)

emdash的unicode等价物是\u2014。您可以使用此unicode与html进行比较。

HTML meta的默认编码设置为UTF,因此所有实体都转换为UTF-8。阅读更多https://developer.mozilla.org/en/docs/Web/HTML/Element/meta#Attributes

&#13;
&#13;
var dash = document.getElementById('dash').innerText;

alert(dash === '\u2014');
&#13;
<div id="dash">&mdash;</div>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

您可以创建一个新的DOM元素,然后比较两者:

/**
 * Test that a DOM element's inner HTML is === &mdash;
 */
function mdashTest(el) {
    var tempEl = document.createElement('div');
    tempEl.innerHTML = '&mdash;';

    return el.innerHTML === tempEl.innerHTML;
}

// Test it!
elem = document.getElementById('dash');
alert( mdashTest( elem ) );
<div id="dash">&mdash;</div>

答案 2 :(得分:2)

我建议:

  1. DOMParser()
  2. function parseToText(code) {
      return new DOMParser().parseFromString('<em>' + code + '</em>', "text/html").firstChild.textContent;
    }
    var is = document.getElementById('text').innerHTML == parseToText("&mdash;");
    document.write("isEquals ", is, parseToText("&mdash;"));
    <em id="text">&mdash;</em>

    1. 或者,使用jQuery:
    2. function parseToText(code) {
        return $("<em>" + code + "</em>").html()
      }
      var isEquals = document.getElementById('text').innerText == parseToText("&mdash;");
      document.write("isEquals ", isEquals);
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
      <em id="text">&mdash;</em>

      1. 或者,使用纯JavaScript:
      2. function parseToText(code) {
          return document.createRange().createContextualFragment(code).firstChild.textContent;
        }
        var isEquals = document.getElementById('text').innerText == parseToText("&mdash;");
        document.write("isEquals ", isEquals);
        <em id="text">&mdash;</em>