A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/javascript-regexp-b-metacharacter/ below:

JavaScript RegExp \b Metacharacter - GeeksforGeeks

JavaScript RegExp \b Metacharacter

Last Updated : 11 Jul, 2025

The \b metacharacter in JavaScript regular expressions represents a word boundary, allowing you to match positions where a word begins or ends. A word boundary is the position between a word character (\w: letters, digits, or underscores) and a non-word character (\W: everything else, including spaces and punctuation).

JavaScript
let str1 = "word";
let str2 = "wordplay";
let regex = /\bword\b/;
console.log(regex.test(str1)); 
console.log(regex.test(str2)); 
Syntax:
/\bpattern\b/
Key Points Real-World Examples 1. Matching Whole Words JavaScript
let regex = /\bcats\b/;
let str1 = "cats are cute";
let str2 = "concatsenate";
console.log(regex.test(str1)); 
console.log(regex.test(str2)); 

Here, \b ensures "cats" is matched only as a whole word.

2. Finding Words at the Start or End JavaScript
let regexStart = /\bstart/;
let regexEnd = /end\b/;

console.log(regexStart.test("start of the sentence")); 
console.log(regexEnd.test("the sentence ends here")); 

Word boundaries allow matching at the start or end of words.

3. Splitting Words Using \b JavaScript
let str = "one, two, three!";
let regex = /\b/;
console.log(str.split(regex)); 

Output
[ 'one', ', ', 'two', ', ', 'three', '!' ]

Splitting a string using \b results in parts separated at word boundaries.

4. Extracting Words JavaScript
let regex = /\b\w+\b/g;
let str = "Extract words from this sentence.";
console.log(str.match(regex)); 

Output
[ 'Extract', 'words', 'from', 'this', 'sentence' ]

The \b metacharacter ensures only whole words are matched.

5. Case-Sensitive Matching JavaScript
let regex = /\bhello\b/i;
console.log(regex.test("Hello world")); 
console.log(regex.test("hello-world")); 
console.log(regex.test("helloworld")); 

Using \b ensures "hello" is recognized as a separate word, even with case-insensitive matching.

When Not to Use \b

Non-Word Characters: If your pattern includes symbols, \b may not work as expected.

JavaScript
let regex = /\b#tag\b/;
console.log(regex.test("#tag"));
Why Use the \b Metacharacter? Conclusion

The \b metacharacter is a powerful tool for identifying and isolating words in a string, ensuring precision and efficiency in regular expression operations.

Recommended Links:

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