Phi*_*hil 5 javascript string search jquery
我需要检查一个字符串是否有三个子串中的一个,如果是,则实现一个函数.我知道我可以检查一个子字符串使用if (str.indexOf("term1") >= 0)但有没有办法检查多个子字符串,而不是使用此代码的几个实例?
TIA
Yas*_*e K 12
这可以动态而优雅地实现您想要做的事情
const terms = ["term1", "term2", "term3"]
const str = "very large string to check for term1, tern2, etc ..."
// check if the string has some of the terms
const result1 = terms.some(term => str.includes(term))
// check if the string has all the terms
const result2 = terms.every(term => str.includes(term))
Run Code Online (Sandbox Code Playgroud)
这也使得为子字符串数组过滤字符串数组变得容易
const terms = ["term1", "term2", "term3"]
const strings = ["very large string text ....", "another large string text"]
// filter the strings of the array that contain some of the substrings we're looking for
const result1 = strings.filter(str => terms.some(term => str.includes(term)))
// filter the strings of the array that contain all the substrings we're looking for
const result2 = strings.filter(str => terms.every(term => str.includes(term)))
Run Code Online (Sandbox Code Playgroud)
elr*_*ado 11
if (/term1|term2|term3/.test("your string")) {
//youre code
}
Run Code Online (Sandbox Code Playgroud)
你可以使用一个循环.甚至可能创建一个这样的辅助函数:
function ContainsAny(str, items){
for(var i in items){
var item = items[i];
if (str.indexOf(item) > -1){
return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
你可以这样打电话:
if(ContainsAny(str, ["term1", "term2", "term3"])){
//do something
}
Run Code Online (Sandbox Code Playgroud)
也许这个:
if (str.indexOf("term1") >= 0 || str.indexOf("term2") >= 0 || str.indexOf("term3") >= 0)
{
//your code
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6748 次 |
| 最近记录: |