HappyHands31
HappyHands31

Reputation: 4101

Regex to match any character from particular string

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:

enter image description here

'A crew that boards the ship', 'chris' => false because:

enter image description here

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

Answers (3)

Kamil Kiełczewski
Kamil Kiełczewski

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

Pointy
Pointy

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

Pac0
Pac0

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

Related Questions