Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for special characters JavaScript

Say I have this HTML element:

<td>&mdash;</td>

When parsed by browsers, &mdash; is converted to an actual em-dash, like so:

<td>—</td>

How can I test for &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
like image 464
vqdave Avatar asked Feb 09 '23 23:02

vqdave


1 Answers

You could create a new DOM element, and compare the two:

/**
 * 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>
like image 93
rnevius Avatar answered Feb 11 '23 13:02

rnevius