Search code examples
javascriptecmascript-6include

Check for multiple values with JS include


There is a function that checks the content of the url with window.location.href. If the URL contains a specific string it should return true:

const doesItContain = () => {
  const url = window.location.href;
  return url.includes('/items');
};

This works fine, if the url contains /items it returns true. The issue comes when it needs to check for multiple strings (multiple pages) and return true if one of them are present. For example:

const doesItContain = () => {
  const url = window.location.href;
  return url.includes('/items', '/users');
};

It returns true only for the first string in the list. Is there a way to check for both or more than one string?


Solution

  • String.prototype.includes expects one argument. The other arguments are ignored.

    You can use some to iterate an array of strings and check if at least one element fullfils the condition:

    const doesItContain = () => {
      const url = window.location.href;
      return ['/items', '/users'].some(el => url.includes(el));
    };