[英]Regex to match any character from particular string
基本上我正在尝试查看名称中的字符是否按顺序出现在字符串的字符中。
即'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'));
将名称转换为单个正则表达式:
let nameregex = new RegExp(".*" + name.split("").join(".*") + ".*");
那你只需要测试:
return nameregex.test(str);
为了避免名称中正则表达式元字符的潜在问题,它必须得到一点点发烧友。
简单方案:
在每个字符之间使用.*
将搜索字词更改为正则表达式。
例如, "chris"
- > "c.*h.*r.*i.*s"
尝试
let re = new RegExp([..."chris"].join`.*`); console.log( re.test('Across the rivers') ); console.log( re.test('A crew that boards the ship') );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.