0

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?

4 Answers 4

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

2

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$/

Comments

1

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))

Comments

-1

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");
}

2 Comments

I've made the same mistake today - String.prototype.contains() is the old name for String.prototype.includes() - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… . Also note that it's compatible only with FF and Chrome for now.
Yeah, but String.prototype.includes() isn't really "old" itself. It's part of the ECMAScript 2015 standard, which, as noted, isn't widely implemented. And I'm not sure why you assume that the OP's question involves a web browser environment at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.