Obi Onuorah Obi Onuorah - 2 months ago 6
Javascript Question

Javascript "".length returning 1 rather than 0

Ok so I am rather stumped by this one.
I get a string value from a javascript library. I call

myStringVar = myStringVar.trim()
but when I do
it gives me an empty string. When I call
var arr = myStringVar.split('')
the first element in the array is and empty string, and when I call arr[0].trim().length it returns 1 instead of zero.

enter image description here

Am I missing something?

Following the comments and responses I have been able to isolate the problem down to the existence of a non-visual unicode character at the beginning of the string. I will now try to find a way to remove those characters from the string....or better yet extract the portions of the string that are of interest.
Thanks for the help.


The most likely answer for this is that you have some invisible Unicode character in your string (for instance, "⁣", U+2063 INVISIBLE SEPARATOR).
A string containing only such a character would look to a user (or programmer) like an empty string, but would infact have length 1 since it does contain a character.

One simple way to test if this is the case, is to get the Unicode character code of the character in the string with string.charCodeAt(0). You can then look this up value in a Unicode table (such as this one), which should tell you if you have an invisible character in your string.