1

How can I find a word with regular expression in Javascript?

For example:

http://127.0.0.1/w/?id=2&tab=wow

I want to know if this link contains the word 'tab'.

1

2 Answers 2

3
var string = 'http://127.0.0.1/w/?id=2&tab=wow'
var containsTab = string.indexOf('tab') > -1

Or if you really want to use a regex:

var containsTab = string.match(/tab/);
Sign up to request clarification or add additional context in comments.

4 Comments

Tab could be contained in a string and still return an index of zero. indexOf() returns -1 for not-found.
Since this is an accepted answer, please update your regexp to include word boundaries, like this /\btab\b/. This is so that words like stable do not trigger a match.
@Marko - the OP didn't mention anything about NOT finding the word stable.
@jahroy - In fact he was pretty clear by asking for word and not a substring. (Maybe he even wanted to know whether there is a query string parameter named tab but didn't ask properly; I'm not going into that.)
1
  1. jQuery is not a language. It's a library written for JavaScript.
  2. You don't need a regular expression.
  3. Use indexOf.

    var str = 'http://127.0.0.1/w/?id=2&tab=wow';
    
    if(str.indexOf('tab') > -1) {
        // Contains string
    } else {
        // Doesn't
    }
    

3 Comments

Does the string stable contain the word tab? In your case, yes. And this is obviously wrong answer.
@MarkoDumic: Yes, stable does contain the word tab.
The OP mentions nothing about exluding stable.

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.