Q:

Make str.index() match only whole words

I want to match whole words using the JS function "index()"
I want to return -1 on this:
var str="hello I am a string";

alert(str.index("str")); //it matches because of STRing, but don't want

Edit: But I strictly want to match "str" only when it appears sorounded by two spaces (but also matching when it is at the beginning/end of a sentence). So \b don't work for me because I do NOT want to allow "hello I am str. how are you?"to match

A:

You can use the word you want to search for and put (^|\s) on one side, which means either the beginning of the string or a whitespace character, and ($|\s) on the right side, which means the end of the string or a whitespace character:
var str = "hello I am a string";

alert(str.search(/(^|\s)str($|\s)/)); // alerts -1
alert(str.search(/(^|\s)string($|\s)/)); // alerts 12

A:

Maybe this will work:
(^|\s)str(\s|$)

