Why does the javascript String whitespace character not match?
That's because the no breaking space (charCode 160) does not exactly equal to space (charCode 32)
jquery's .text()
encodes HTML entities to their direct unicode equivalence, and so
becomes String.fromCharCode(160)
You can solve it by replaceing all the the non-breaking spaces with ordinary spaces:
d.text().replace(String.fromCharCode(160) /* no breaking space*/,
" " /* ordinary space */) == "some text"
or better yet:
d.text().replace(/\s/g /* all kinds of spaces*/,
" " /* ordinary space */) == "some text"
is not the same as the space character (Unicode U+0020). It's a non-breaking space character, encoded in Unicode as U+00A0. This is why the first of your tests doesn't match, but the third one does; \s
matches all white space characters.
Either stick to your regular expression test, or use \u00a0
or \xa0
in your equality check:
$("#text").text().trim() === "some\xa0text";
$("#text").text().trim() === "some\u00a0text";
It is not taking into consideration the '\n' that are invisible. Get rid of the '\n' and check it with '=='.
Try This
var x = $("#text").html();
x = x.replace(/(\r\n|\n|\r)/gm, "");
x = x.replace(/\s+/g, '');
alert(x);
if (x == 'some text') {
alert('true');
}
else {
alert('false');
}
Hope this helps.