Last Updated : 10 Dec, 2024
The \w metacharacter in JavaScript regular expressions matches any word character. A word character is defined as:
It does not match spaces, punctuation, or other non-alphanumeric characters.
JavaScript
let regex = /\w/;
let str1 = "hello123";
let str2 = "!@#";
console.log(regex.test(str1));
console.log(regex.test(str2));
The pattern \w matches any word character in str1 but not in str2, as it contains only special characters.
Syntax:/\w/
let regex = /\w/;
let str = "Regex is fun!";
console.log(regex.test(str));
Checks if the string contains any word characters.
2. Matching Consecutive Word Characters JavaScript
let regex = /\w+/g;
let str = "hello_world 123";
let matches = str.match(regex);
console.log(matches);
[ 'hello_world', '123' ]
The \w+ matches one or more word characters in sequence.
3. Replacing Non-Word Characters JavaScript
let str = "hello, world!";
let cleanedStr = str.replace(/\W+/g, " ");
console.log(cleanedStr);
Replaces all non-word characters (\W) with spaces.
4. Validating Usernames JavaScript
let regex = /^\w+$/;
let username1 = "user_name123";
let username2 = "invalid@user";
console.log(regex.test(username1));
console.log(regex.test(username2));
Ensures the username contains only word characters.
5. Counting Word Characters JavaScript
let str = "Hello 123!";
let regex = /\w/g;
let count = (str.match(regex) || []).length;
console.log(count);
Counts the total number of word characters in a string.
Common Patterns Using \w/\w/
/\w+/
str.replace(/\W/g, "");
/^\w+$/
str.match(/\w+/g);Limitations
The \w metacharacter is a versatile and frequently used tool in regular expressions for matching alphanumeric and underscore characters.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4