英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论