Pietro Coelho
Pietro Coelho

Reputation: 2072

Regular expression for check if string has two specified words javascript

I want to create a function that returns true if the string has these two words: "team" and "picture".

The format of the string will be: "team_user_picture" (example) where "user" can be a different string.

I tried /team picture/ but this doesn't work for my case. How can I do that using a regular expression?

Upvotes: 0

Views: 1528

Answers (4)

Downgoat
Downgoat

Reputation: 14361

This is a job for indexOf. RegEx is inefficient for this task:

function hasWords(string) {
    return ~string.indexOf("picture") &&
           ~string.indexOf("team");
}

An even better function would be:

function contains(str, ar) {
    return ar.every(function(w) {
        return ~str.indexOf(w);
    });
}

Now you can do:

contains("team_user_picture", ["team", "picture"])

This will check if the first string has all of the words in the array.


ES6:

const contains = (s, a) => a.every(w => s.includes(w))

alternatively:

const contains = (s, a) => a.every(w => s[
    String.prototype.contains ?
    'contains' : 'include'
](w))

Upvotes: 1

Amit
Amit

Reputation: 46323

If you want to test of the string contains both words, regardless of order:

var s = 'team_user_picture';

var re = /(team.*picture)|(picture.*team)/;

alert(re.test(s));

If you want exact validation against your template, use:

/^team_.+_picture$/

Upvotes: 2

Jan Böcker
Jan Böcker

Reputation: 190

If all you want to do is to ensure that both words are in the string, regular expressions are overkill. Just use the contains() method like this:

function check(str) {
    return str.contains("team") && str.contains("picture");
}

Upvotes: -1

dhouty
dhouty

Reputation: 1989

If "team" always comes before "picture", then /team.*picture/ will work.

Then the function to test that regex would be

function hasKeywords(str) {
    return /team.*picture/.test(str);
}

Upvotes: 2

Related Questions