JavaScript RegExp \B Metacharacter
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.
let regex = /\Bcat\B/;
let str1 = "concat";
let str2 = "cat";
console.log(regex.test(str1));
console.log(regex.test(str2));
Output
false false
The pattern \Bcat\B matches "cat" only if it is not at the beginning or end of a word.
Syntax:
let regex = /\Bpattern\B/;
- \B: Matches a position where no word boundary (\b) exists.
Key Points
- Matches positions inside a word, not at the start or end.
- Useful for precise control over word-boundary-sensitive patterns.
- Often used to restrict matches to non-boundary contexts.
Real-World Examples
1. Matching Inside Words
let regex = /\Bcat\B/;
let str1 = "concatenate";
let str2 = "catapult";
console.log(regex.test(str1));
console.log(regex.test(str2));
Output
true false
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
let regex = /\Bing/;
let str1 = "running";
let str2 = "ing";
console.log(regex.test(str1));
console.log(regex.test(str2));
Output
true false
The \Bing matches "ing" only when it is not at the start of the word.
3. Highlighting Non-Boundary Matches
let regex = /\Bis\B/g;
let str = "This island is beautiful.";
let matches = str.match(regex);
console.log(matches);
Output
null
The \B ensures only the "is" within "This" is matched, not the standalone "is."
4. Removing Characters Within Words
let str = "hello1world2";
let regex = /\B\d\B/g;
let result = str.replace(regex, "");
console.log(result);
Output
helloworld2
The \B\d\B matches digits (\d) that are surrounded by word characters and removes them.
5. Preventing Word Boundary Matches
let regex = /\Bis/;
let str = "island";
console.log(regex.test(str));
Output
false
The \Bis matches "is" only when it is not at the start of a word.
Common Patterns Using \B
- Match Inside Words Only:
/\Bword\B/
- Find Suffixes Without Word Endings:
/\Bing/
- Remove Inner Digits:
str.replace(/\B\d\B/g, "");
- Highlight Internal Patterns:
/in\B/g
- Prevent Full Word Matches:
/prefix\B/
Limitations
- Context-Specific: Only useful in cases where non-boundary detection is necessary.
- Non-Intuitive: Can be confusing when combined with quantifiers or other regex elements.
Why Use \B Metacharacter?
- Precise Matching: Helps identify patterns inside words, avoiding boundaries.
- Text Parsing: Useful for extracting substrings or cleaning text data.
- Control Over Context: Provides fine-grained control in scenarios where boundary matching (\b) is insufficient.
Conclusion
The \B metacharacter is a powerful but specialized tool in regex, enabling precise pattern matching where word boundaries do not exist.
Recommended Links:
- JavaScript RegExp Complete Reference
- JavaScript Cheat Sheet-A Basic guide to JavaScript
- JavaScript Tutorial