0

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?

2 Answers 2

2

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));
};
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

2 Comments

can you provide a way to dynamically create the regex for different situations
@YoussefHossam Yes, use the RegExp constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.