Reputation: 333
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 ) );
Upvotes: 1
Views: 891
Reputation: 23869
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
.
Upvotes: 4