Reputation: 4101
Basically I'm trying to see if the characters of a name appear in the characters of a string in order.
I.e. 'Across the rivers', 'chris'
=> true
because:
'A crew that boards the ship', 'chris'
=> false
because:
I have this:
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'));
But as you can see I don't know how to test for when a single character matches any character from name
. Is there a simple way to do this with a regex?
EDIT - TESTING NEW METHOD
function nameInStr(str, name){
let nameregex = new RegExp(".*" + name.split("").join(".*") + ".*");
return str.test(nameregex);
}
console.log(nameInStr('Across the rivers', 'chris'));
Upvotes: 3
Views: 1164
Reputation: 92427
Try
let re = new RegExp([..."chris"].join`.*`);
console.log( re.test('Across the rivers') );
console.log( re.test('A crew that boards the ship') );
Upvotes: 3
Reputation: 413737
Turn the name into a single regular expression:
let nameregex = new RegExp(".*" + name.split("").join(".*") + ".*");
then you just have to test:
return nameregex.test(str);
It'd have to get a little fancier to avoid potential problems with regular expression metacharacters in the name.
Upvotes: 3
Reputation: 23174
Simple solution :
Change your search term to a regex with .*
in between every character.
For instance, "chris"
-> "c.*h.*r.*i.*s"
Upvotes: 3