Reputation: 649
I've just needed to compare to strings in JavaScript, and the comparision of specific strings failed sometimes.
One value was obtained with jQuery via the text()
method (from some auto-generated HTML):
var value1 = $('#somelement').text();
The other value is hardcoded in a JavaScript file (from me).
After some testing I found that these strings have different encodings, which became clear when I logged them with the escape()
function.
Firebug showed me something like this:
console.log(escape(value1));
"blabla%A0%28blub%29"
console.log(escape(value2));
"blabla%20%28blub%29"
So at the end it's the whitespace with different encodings which made my comparison fails.
So my question is: how to handle this correctly? Can I just replace the whitespace to be equal? But I guess there are other control characters - like tab, return and so on - which could mess up my comparison?
Upvotes: 4
Views: 329
Reputation: 664579
So at the end it's the whitespace with different encodings which made my comparison fails.
No, it is not a different encoding. It is just a different whitespace - a non-breaking space.
Can I just replace the white space to be equal? But I guess there are other control characters - like tab, return and so on - which could mess up my comparison?
You can replace all of them. You might want to try something like
value1.replace(/\s+/g, " ").replace(/^\s*|\s$/g, "") == value2
which joins multiple whitespaces (of all kinds, including returns) to a single space and also trims the string before the comparison.
Upvotes: 2