javascript - How is it possible for an empty string to have a length greater than 0? - Stack Overflow

I came across this bug while trying to run a JS conditional to check for an empty string. In Chrome deb

I came across this bug while trying to run a JS conditional to check for an empty string. In Chrome debugger, the empty string evaluates with a length of 1 and sometimes even 2. It's happening in a react app. I'm pretty lost as to how the proto still works correctly but the normal length method doesn't.

I came across this bug while trying to run a JS conditional to check for an empty string. In Chrome debugger, the empty string evaluates with a length of 1 and sometimes even 2. It's happening in a react app. I'm pretty lost as to how the proto still works correctly but the normal length method doesn't.

Share Improve this question edited Dec 11, 2018 at 22:55 Geek Num 88 5,3122 gold badges23 silver badges36 bronze badges asked Nov 30, 2018 at 17:57 Jeremy GottfriedJeremy Gottfried 1,20116 silver badges32 bronze badges 5
  • 1 Is it whitespace? Or possibly a line break? – Ryan Wilson Commented Nov 30, 2018 at 17:59
  • 1 Are you sure that there is no character? Maybe you just can't see it ... – Jonas Wilms Commented Nov 30, 2018 at 18:00
  • 3 An empty string, by definition, has 0 characters. Thus the string shown is not empty: even if there are no visible characters. Use value.charCodeAt(0) to see what character is really there (value[0] won't be useful because it returns a string itself). – user2864740 Commented Nov 30, 2018 at 18:00
  • Just tried on Chrome console. value = '' value.length // 0 – pmkro Commented Nov 30, 2018 at 18:01
  • 2 Ah yes, charCodeAt worked, thanks! It's apparently an enter – Jeremy Gottfried Commented Nov 30, 2018 at 18:04
Add a ment  | 

2 Answers 2

Reset to default 3

A string may appear visibly empty when you ask for its value if the string contains characters that are not normal characters. These strings could be generated via the String.fromCharCode method or implicitly like '\x0d'. Characters such as Enter will appear to be an empty string. You can check for invisible characters using the charCodeAt method.

As Matus showed, this will replicate the behavior in question:

v = '\x0d'

console.log(v);        // ""
console.log(typeof v); // "string"
console.log(v[0]);     // "" 
console.log(v.length); // "1"

It is probably on of these cases (invisible characters)

v = '\x0d'

console.log(v);        // ""
console.log(typeof v); // "string"
console.log(v[0]);     // "" 
console.log(v.length); // "1"


v = '\x0d\x0d'

console.log(v);        // ""
console.log(typeof v); // "string"
console.log(v[0]);     // "" 
console.log(v.length); // "2";

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745515047a4630945.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信