0

Why does startsWith method return true when the searchString is empty. I think same in other string methods like includes, endsWith. What can I do if I want to avoid it i.e. it should return false in case of empty searchString.

var haystack = 'Hello World!', needle ='';
console.log( haystack.startsWith( needle ) );
Ashish
  • 313
  • 1
  • 5
  • 14

1 Answers1

3

Because it is designed to return so. Empty strings denote the existence of 0 characters. That's why, in a way, every string at least starts with blank.

If you still want to return false, you can do it like so:

var haystack = 'Hello World!',
  needle = '';
console.log(Boolean(needle) && haystack.startsWith(needle));

Check for the boolean equivalent of the checker string first, so that if it is blank, the return value becomes false.

31piy
  • 23,323
  • 6
  • 47
  • 67