JavaScript RegExp B Metacharacter (original) (raw)

Last Updated : 10 Dec, 2024

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.