Javascript RegExp-Jack{ja)-Jones{jo}-片段搜索
我有一个具有以下结构的用户列表:Javascript RegExp-Jack{ja)-Jones{jo}-片段搜索,javascript,regex,search,Javascript,Regex,Search,我有一个具有以下结构的用户列表: const users = [ { full_name: "Jack Jones", email: "jack.jones@email.com", id: 123 }, { full_name: "Jack Jameson", email: "jack.jameson@email.com", id: 456 } ] 我
const users = [
{
full_name: "Jack Jones",
email: "jack.jones@email.com",
id: 123
},
{
full_name: "Jack Jameson",
email: "jack.jameson@email.com",
id: 456
}
]
我需要使用带有规则的RegExp使用输入进行过滤:
Trim whitespaces from input.value
input === "ja" returns "Jack Jones" and "Jack Jameson"
input === "jo" returns "Jack Jones"
input === "ja jo" returns "Jack Jones"
input === "ac on" returns "Jack Jones" and "Jack Jameson"
我尝试过:
^(?=.*\bvar\b)(?=.*\bvar2\b)。*$
但它不能正常工作。您可以执行以下操作:
const arr=[
{
全名:“杰克·琼斯”,
电子邮件:“杰克。jones@email.com",
身份证号码:123
},
{
全名:“杰克·詹姆逊”,
电子邮件:“杰克。jameson@email.com",
身份证号码:456
}];
让输入=“ja-jo”;
让inputParts=input.split(“”);
设结果=arr;
inputParts.forEach(part=>result=result.filter(user=>user.full_name.toLowerCase().includes(part.toLowerCase()));
console.log(result);
我尝试了两种解决方案。@Zahids one对我有效,但我选择了在中找到的RegExps“lookaheads”
解决方案regExp
如下所示:
“^(?=.*\\b”+var+.*\\b)。*$”
所以在我的例子中,我有构建函数:
function search(item, query) {
// 1. takes all wards
const inputs = query.split(" ");
// 2. build regExp fragments like the example above
const regexFrags = inputs.reduce((phrases, next) => {
phrases.push("(?=.*\\b" + next.trim() + ".*\\b)");
return phrases;
}, []);
// 3, build final regExp string
const regexString = "^" + regexFrags.join("") + ".*$";
// 4. build regExp Object with options
const regExp = new RegExp(regexString, "gmiu");
// 5. finally test the string
return regExp.test(item.full_name);
}
链接至我确实工作过,谢谢@Zahid。询问“请帮助我”的问题往往需要高度本地化的指导,或者在某些情况下,需要持续或私人的帮助,这不适合我们的问答格式。它也相当模糊,最好用更具体的问题代替。请阅读。
function search(item, query) {
// 1. takes all wards
const inputs = query.split(" ");
// 2. build regExp fragments like the example above
const regexFrags = inputs.reduce((phrases, next) => {
phrases.push("(?=.*\\b" + next.trim() + ".*\\b)");
return phrases;
}, []);
// 3, build final regExp string
const regexString = "^" + regexFrags.join("") + ".*$";
// 4. build regExp Object with options
const regExp = new RegExp(regexString, "gmiu");
// 5. finally test the string
return regExp.test(item.full_name);
}