基本上,我试图查看名称的字符是否按顺序出现在字符串的字符中。
即'Across the rivers', 'chris'
=> true
因为:
'A crew that boards the ship', 'chris'
=> false
因为:
我有这个:
function nameInStr(str, name){
let stringArray = Array.from(str);
let testName = "";
for (let i = 0; i < stringArray.length; i++) {
if (stringArray[i].match(/any character from name/)) {
testName += stringArray[i];
}
}
if (testName === name) {
return true;
}
else {
return false;
}
}
console.log(nameInStr('Across the rivers', 'chris'));
但是如您所见,我不知道如何测试单个字符与name
中的任何字符是否匹配。有没有一种简单的方法可以使用正则表达式来做到这一点?
编辑-测试新方法
function nameInStr(str, name){
let nameregex = new RegExp(".*" + name.split("").join(".*") + ".*");
return str.test(nameregex);
}
console.log(nameInStr('Across the rivers', 'chris'));
答案 0 :(得分:3)
将名称转换为单个正则表达式:
let nameregex = new RegExp(".*" + name.split("").join(".*") + ".*");
然后您只需要测试:
return nameregex.test(str);
必须避免一些麻烦,以避免名称中的正则表达式元字符可能引起的问题。
答案 1 :(得分:3)
简单的解决方案:
将搜索词更改为每个字符之间使用.*
的正则表达式。
例如,"chris"
-> "c.*h.*r.*i.*s"
答案 2 :(得分:3)
尝试
let re = new RegExp([..."chris"].join`.*`);
console.log( re.test('Across the rivers') );
console.log( re.test('A crew that boards the ship') );