javascript - How to Regular expression to match only some words? -


i want return true using javascript regex.test() method if string contains words list hello,hi,what,why,where , not other words.

i tried following regex failed isolate words, , return if other words present.

/(hello)|(hi)|(what)|(why)|(where)/gi.test(string) 

examples

string hello world should false because of world

string hello hi what should true

string hello hi word should false because of world

string hello where should true

string where is should false because of is

string where why should true

string where why is should false because of is

string hello should true

string hello bro should false because of bro

means string should contains words hello,hi,what,why,where

function test1 ( str ) {    return /^(\s*(hello|hi|what|why|where)(\s+|$))+$/i.test( str );  }      console.log( test1("hello what") ); // true  console.log( test1("hello there") );      // false

^ $ start end of string there should be
^( )+$ 1 or more of
^( (hello|hi) )+$ words, word can
^(\s*(hello|hi) )+$ prefixed 0 or more spaces,
^(\s*(hello|hi)(\s+ ))+$ , suffixed 1 or more spaces
^(\s*(hello|hi)(\s+|$))+$ or end of string.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -