I'm getting unexpected results with this code:
'foo'.match(new RegExp('\bfoo\b')); // Returns null
Why is this returning null
while this one returns "foo"?
'foo'.match(new RegExp('foo')); // Returns "foo"
Doesn't a word boundary marker match the beginning and end as well?
EDIT: I need the regular expression itself to be a string because I am injecting variables into it.
Simply put, the word boundary \b allows you to carry the match the whole word using a regular expression in the following form: \bword\b. Code language: JavaScript (javascript) For example, in the string Hello, JS!
JavaScript match() Function. The string. match() is an inbuilt function in JavaScript used to search a string for a match against any regular expression. If the match is found, then this will return the match as an array.
The RegExp \B Metacharacter in JavaScript is used to find a match which is not present at the beginning or end of a word. If a match is found it returns the word else it returns NULL.
Thus, the word boundary will match after the -, and so will not capture it. Word boundaries match before the first and after the last word characters in a string, as well as any place where before it is a word character or non-word character, and after it is the opposite.
Simply put, the word boundary \b allows you to carry the match the whole word using a regular expression in the following form: For example, in the string Hello, JS! the following positions qualify as a word boundary: The following example returns 'JS' because 'Hello, JS!' matches the regular expression /\bJS\b/:
There are three different positions that qualify as word boundaries: At string start, if the first string character is a word character \w. Between two characters in the string, where one is a word character \w and the other is not. At string end, if the last string character is a word character \w.
A word boundary, in most regex dialects, is a position between \w and \W (non-word char), or at the beginning or end of a string if it begins or ends (respectively) with a word character ( [0-9A-Za-z_] ). So, in the string "-12", it would match before the 1 or after the 2.
Escape the backslashes
'foo'.match(new RegExp('\\bfoo\\b'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With