Home > Web Front-end > JS Tutorial > How to Use Regular Expressions to Match Whole Words in JavaScript?

How to Use Regular Expressions to Match Whole Words in JavaScript?

Susan Sarandon
Release: 2024-12-22 13:17:10
Original
918 people have browsed it

How to Use Regular Expressions to Match Whole Words in JavaScript?

How to Match a Specific Word Using Regular Expressions in JavaScript

In JavaScript, searching for a whole word within a string can be achieved with regular expressions. Here's a step-by-step guide on how to implement this functionality:

Step 1: Define the Regular Expression Pattern

To match a whole word, you can use the following regular expression pattern:

\b(pattern)\b
Copy after login

where pattern represents the word you want to search for and b is a word boundary anchor that ensures the search matches the beginning or end of the word.

Step 2: Creating a Dynamic Regular Expression

If the word you want to match is user-defined, you can create a dynamic regular expression using JavaScript's RegExp object:

new RegExp("\b" + lookup + "\b")
Copy after login

Step 3: Perform the Search

Once you have the dynamic regular expression, you can use the test() method on the regular expression object to perform the search:

new RegExp("\b" + lookup + "\b").test(textbox.value)
Copy after login

where textbox.value is the string in which you want to search.

Example

Consider the following example:

var lookup = '\n\n\n\n\n\n2    PC Games        \n\n\n\n';
lookup = lookup.trim();
var tttt = 'tttt';
alert((new RegExp("\b" + lookup + "\b")).test(2)); // true
Copy after login

This example searches for the word "lookup" in the lookup string and returns true because the word is found.

Important Note

Remember to use the correct direction when testing the regular expression. In the example above, the test is written as:

alert((new RegExp("\b" + lookup + "\b")).test(2));
Copy after login

instead of:

alert((new RegExp("\b" + lookup + "\b")).test(lookup));
Copy after login

which would incorrectly search for the word "2" within the lookup string.

The above is the detailed content of How to Use Regular Expressions to Match Whole Words in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template