How can I match a whole word in JavaScript?
I am trying to search a single whole word through a textbox. Say I search "me", I should find all occurrences of the word "me" in the text, but not "memmm" per say.
I am using JavaScript's search('my regex expression')
to perform the current search (with no success).
After several proposals to use the \b
switches (which don't seem to work) I am posting a revised explanation of my problem:
For some reason this doesn't seem to do the trick. Assume the following JavaScript search text:
var lookup = '\n\n\n\n\n\n2 PC Games \n\n\n\n';
lookup = lookup.trim() ;
alert(lookup );
var tttt = 'tttt';
alert((/\b(lookup)\b/g).test(2));
Moving lines is essential
Solution 1:
To use a dynamic regular expression see my updated code:
new RegExp("\\b" + lookup + "\\b").test(textbox.value)
Your specific example is backwards:
alert((/\b(2)\b/g).test(lookup));
Regexpal
Regex Object
Solution 2:
Use the word boundary assertion \b
:
/\bme\b/
Solution 3:
You may use the following code:
var stringTosearch ="test ,string, test"; //true
var stringTosearch ="test string test"; //true
var stringTosearch ="test stringtest"; //false
var stringTosearch ="teststring test"; //false
if (new RegExp("\\b"+"string"+"\\b").test(stringTosearch)) {
console.log('string found');
return true;
} else {
return false;
}