我正在搜索特定长字符串中的字符串列表。
想象一下,长流是:Jim participates in a free wrestling competition
,数组为:["Jim","free","not","me","you","wrestling"]
问题是我只想要检索名称而不是其他部分。
在上面的例子中我只需要" Jim"而不是"免费"或者"摔跤"。
顺便说一句,名字可以在数组的任何位置。这是我的代码。
title = document.getElementById("title").value
cat_list = document.getElementById("category-all").textContent.replace(/\n\n/g, "\n").replace(/^\s*/g, "").trim().split("\n");
for(i = 0; i < cat_list.length; i++){
if(title.indexOf(cat_list[i]) > -1){
return cat_list[i]
}
}
如何将此条件插入我的代码?
答案 0 :(得分:0)
假设您调用名称的内容只是一个string
而您正在寻找交叉点:
var str = "Jim participates in a free wrestling competition"
var arr1 = ["Jim","free","not","me","you","wrestling"]
var arr2 = str.split(" ")
array1.filter((n) => array2.includes(n))
有关详情,请参阅this question。
如果您正在寻找特殊名称(如人名),除了检查是否是标题案例之外别无他法;但任何名称是句子的第一个单词都是标题案例。所以,它打破了你的情况。
答案 1 :(得分:0)
你可以在数组中找到你想要的元素的索引,然后在ES6中得到它:
const cat_list = ["Jim","free","not","me","you","wrestling"];
let nameIndex = cat_list.findIndex(x => x.toString().trim().toUpper() === 'JIM');
//instead of hardcoding try to find a way to generalize it like cat_list[name] or something
const name = cat_list[nameIndex];