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-2/ below:

JavaScript RegExp \B Metacharacter - GeeksforGeeks

JavaScript RegExp \B Metacharacter

Last Updated : 05 Aug, 2025

The \B metacharacter in JavaScript regular expressions matches a position where a word boundary does not exist. It is essentially the opposite of the \b (word boundary) metacharacter.

JavaScript
let regex = /\Bcat\B/;
let str1 = "concat";
let str2 = "cat";
console.log(regex.test(str1));
console.log(regex.test(str2)); 

The pattern \Bcat\B matches "cat" only if it is not at the beginning or end of a word.

Syntax:
let regex = /\Bpattern\B/;
Key Points Real-World Examples 1. Matching Inside Words JavaScript
let regex = /\Bcat\B/;
let str1 = "concatenate";
let str2 = "catapult";
console.log(regex.test(str1)); 
console.log(regex.test(str2)); 

The \Bcat\B matches "cat" only within another word, such as "concatenate," but not when it starts or ends a word.

2. Restricting Prefix or Suffix Matches JavaScript
let regex = /\Bing/;
let str1 = "running";
let str2 = "ing";
console.log(regex.test(str1)); 
console.log(regex.test(str2)); 

The \Bing matches "ing" only when it is not at the start of the word.

3. Highlighting Non-Boundary Matches JavaScript
let regex = /\Bis\B/g;
let str = "This island is beautiful.";
let matches = str.match(regex);
console.log(matches);

The \B ensures only the "is" within "This" is matched, not the standalone "is."

4. Removing Characters Within Words JavaScript
let str = "hello1world2";
let regex = /\B\d\B/g;
let result = str.replace(regex, "");
console.log(result);

The \B\d\B matches digits (\d) that are surrounded by word characters and removes them.

5. Preventing Word Boundary Matches JavaScript
let regex = /\Bis/;
let str = "island";
console.log(regex.test(str));

The \Bis matches "is" only when it is not at the start of a word.

Common Patterns Using \B
/\Bword\B/
/\Bing/
str.replace(/\B\d\B/g, "");
/in\B/g
/prefix\B/
Limitations Why Use \B Metacharacter? Conclusion

The \B metacharacter is a powerful but specialized tool in regex, enabling precise pattern matching where word boundaries do not exist.

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