Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 977
vondip Avatar asked Feb 09 '10 22:02

vondip


People also ask

How do you match words in JavaScript?

JavaScript match() Function. The string. match() is an inbuilt function in JavaScript used to search a string for a match against any regular expression. If the match is found, then this will return the match as an array.

What does .match do in JavaScript?

What is the match() method JavaScript? The string. match() is a built-in function in JavaScript; it is used to search a string, for a match, against a regular expression. If it returns an Array object the match is found, if no match is found a Null value is returned.

How do you match strings?

Using String. equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.


2 Answers

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

like image 128
ChaosPandion Avatar answered Sep 22 '22 14:09

ChaosPandion


Use the word boundary assertion \b:

/\bme\b/ 
like image 41
Gumbo Avatar answered Sep 25 '22 14:09

Gumbo