Home >Web Front-end >JS Tutorial >How Can I Match Whole Words in JavaScript Using Regular Expressions?
Matching Whole Words in JavaScript
The task at hand is to locate every instance of a specified whole word within a text field. Consider searching for the term "me." The search should identify all occurrences of "me" in the text, excluding variations like "memmm."
After experimenting with b switches without success, let's delve deeper into the issue. The following JavaScript search text is used:
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));
Dynamic regular expressions are required for effective matching. Here's the revised code:
new RegExp("\b" + lookup + "\b").test(textbox.value)
In the provided example:
alert((/\b(2)\b/g).test(lookup));
the logic is reversed.
Refer to the provided resources for further guidance:
The above is the detailed content of How Can I Match Whole Words in JavaScript Using Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!