Comparing strings with different encodings

I just need to compare with strings in JavaScript and comparing specific strings sometimes fails.

One value was retrieved with jQuery using a method text()

(from some auto-generated HTML):

var value1 = $('#somelement').text();

      

The other meaning is hardcoded in the JavaScript file (from me).

After some testing, I found that these strings have different encodings, which became clear when I registered them with the function escape()

.

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 there are spaces with different encodings that made my comparison fail.

So my question is, how do I do it right? Can I just replace spaces with equals? But I think there are other control characters - like tab, return, etc. - what can spoil my comparison?

+3


source to share


1 answer


So, at the end there are spaces with different encodings that made my comparison fail.

No, this is not another encoding . It's just another gap - an unbreakable space .

Is it possible to just replace white space with equal? But I think there are other control characters - like tab, return, etc. - what can spoil 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 ( all kinds , including returns ) to one place, and also truncates the string before comparing.

0


source







All Articles