MD. Mohiuddin Ahmed
MD. Mohiuddin Ahmed

Reputation: 2182

How can I check if string has particular word in javascript

Now, I know I can calculate if a string contains particular substring.Using this:

if(str.indexOf("substr") > -1){
}

Having my substring 'GRE' I want to match for my autocomplete list:

GRE:Math

GRE-Math

But I don't want to match:

CONGRES

and I particularly need to match:

NON-WORD-CHARGRENON-WORD-CHAR and also
GRE

What should be the perfect regex in my case?

Upvotes: 0

Views: 880

Answers (3)

zx81
zx81

Reputation: 41848

MD, if I understood your spec, this simple regex should work for you:

\W?GRE(?!\w)(?:\W\w+)?

But I would prefer something like [:-]?GRE(?!\w)(?:[:-]\w+)? if you are able to specify which non-word characters you are willing to allow (see explanation below).

This will match

GRE
GRE:Math
GRE-Math

but not CONGRES

Ideally though, I would like to replace the \W (non-word character) with a list of allowable characters, for instance [-:] Why? Because \W would match non-word characters you do not want, such as spaces and carriage returns. So what goes in that list is for you to decide.

How does this work?

\W? optionally matches one single non-word character as you specified. Then we match the literal GRE. Then the lookahead (?!\w) asserts that the next character cannot be a word character. Then, optionally, we match a non-word character (as per your spec) followed by any number of word characters.

Depending on where you see this appearing, you could add boundaries.

Upvotes: 2

Amit Joki
Amit Joki

Reputation: 59292

You can use the regex: /\bGRE\b/g

if(/\bGRE\b/g.test("string")){
  // the string has GRE
}
else{
  // it doesn't have GRE
}

\b means word boundary

Upvotes: 0

sshashank124
sshashank124

Reputation: 32197

Maybe you want to use \b word boundaries:

(\bGRE\b)

Here is the explanation

Demo: http://regex101.com/r/hJ3vL6

Upvotes: 2

Related Questions