Home > Enterprise >  Check for multiple values with JS include
Check for multiple values with JS include

Time:02-06

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?

CodePudding user response:

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));
};

CodePudding user response:

You can use a regular expression, separating each of the strings to check with |.

return /\/items|\/users/.test(url);
  • Related