Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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));
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading