Home >Web Front-end >JS Tutorial >How Can I Match Whole Words in JavaScript Using Regular Expressions?

How Can I Match Whole Words in JavaScript Using Regular Expressions?

Barbara Streisand
Barbara StreisandOriginal
2024-12-07 18:00:17198browse

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:

  • Regexpal: https://regexpal.com/
  • Regex Object: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn