Testing Special JavaScript Characters

Let's say I have this HTML element:

<td>&mdash;</td>

When analyzed by browsers, it is &mdash;converted to the actual em dash, for example:

<td></td>

How can I check &mdash;without using other characters in my JavaScript code?

console.log(elem.innerHTML == "&mdash;"); // false
console.log(elem.textContent == "&mdash;"); // false
console.log(elem.innerHTML == "—"); // true
console.log(elem.textContent == "—"); // true
+4
source share
3 answers

You can create a new DOM element and compare two:

/**
 * Test that a DOM element 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>
Run codeHide result
+3
source

The unicode equivalent of emdash is equal \u2014. You can use this unicode to compare with html.

HTML UTF, UTF-8. https://developer.mozilla.org/en/docs/Web/HTML/Element/meta#Attributes

var dash = document.getElementById('dash').innerText;

alert(dash === '\u2014');
<div id="dash">&mdash;</div>
Hide result
+3

I suggest that:

  • across DOMParser()

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>
Run codeHide result
  1. Or using jQuery:

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>
Run codeHide result
  1. Or using regular JavaScript:

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>
Run codeHide result
+2
source

Source: https://habr.com/ru/post/1609136/


All Articles