Home > Software design >  Why do String.includes acts different with space characters?
Why do String.includes acts different with space characters?

Time:02-17

So, I have this method to check if an object has a specific status:

export const verifyStatus = (productStatus: string, expectedStatus: string): boolean => {
  return productStatus.split(' ').some((status) => expectedStatus.includes(status));
};

I'll use this as my values:

const productStatus = 'POTATO BANANA TOMATO LETTUCE'
const expectedStatus = 'EGG'

The weird thing is, this is false:

'POTATO BANANA TOMATO LETTUCE'
    .split(' ')
    .some((status) => 'EGG'.includes(status));

This is true (notice the double space between POTATO and BANANA)

'POTATO  BANANA TOMATO LETTUCE'
    .split(' ')
    .some((status) => 'EGG'.includes(status));

But this is working despite any double space (true if I add EGG to my first string and false if I remove):

'POTATO BANANA TOMATO LETTUCE'
    .split(' ')
    .some((status) => status.includes('EGG'));
'POTATO  BANANA TOMATO LETTUCE'
    .split(' ')
    .some((status) => status.includes('EGG'));

Why is that happening? Am I missing something? I had this method for about 5 months and it was working perfectly until a few hours ago.

CodePudding user response:

"EGG".includes("") is true. "".includes("EGG") is false. That's why you get different results from the two versions of your code.

Why ""? Because .split(" ") on a string containing two spaces in a row will put a blank string in the array:

console.log("TEST  ING".split(" "));

You can tell split to split on any sequence of spaces using a regular expression -- .split(/ /) for just spaces, or .split(/\s /) for runs of whitespace:

console.log(
    "POTATO  BANANA TOMATO LETTUCE"
        .split(/\s /)
        .some((status) => "EGG".includes(status))
);

CodePudding user response:

(status) => 'EGG'.includes(status) is asking whether the value of status is found somewhere in the string 'EGG'. The empty string '' resulting from the double space is obviously found there in several places.

If you just want to check whether EGG is among the space-separated items, you should use Array.includes:

'POTATO  BANANA TOMATO LETTUCE'
    .split(' ')
    .includes('EGG')
  • Related