使用JS include检查多个数值

huangapple go评论64阅读模式
英文:

Check for multiple values with JS include

问题

以下是已翻译的部分:

如果 URL 包含特定字符串,应该返回 true 的功能是存在的:

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

这个功能在 URL 包含 /items 时返回 true,但当需要检查多个字符串(多个页面)并且如果其中一个存在就返回 true 时会出现问题。例如:

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

它仅对列表中的第一个字符串返回 true。是否有一种方法可以同时检查多个字符串?

英文:

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?

答案1

得分: 2

String.prototype.includes 期望一个参数。其他参数将被忽略。

您可以使用 some 来迭代一个字符串数组,并检查是否至少有一个元素满足条件:

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

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

答案2

得分: 0

你可以使用正则表达式,使用 | 分隔要检查的每个字符串。

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

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

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

huangapple
  • 本文由 发表于 2023年2月6日 03:32:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75354956.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定