Ashish
Ashish

Reputation: 333

startsWith string method with empty searchString

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

Answers (1)

31piy
31piy

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

Related Questions