Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Word boundary won't match the beginning or end in Javascript

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.

like image 457
mattalxndr Avatar asked Feb 17 '11 02:02

mattalxndr


People also ask

What is word boundary in JavaScript?

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!

How do you match words in JavaScript?

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.

What does \b mean in JavaScript?

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.

Does the word boundary match before or after the-?

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.

What is a word boundary in JavaScript?

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

How do you find the word boundary of a string?

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.

What is a word boundary in regex?

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.


1 Answers

Escape the backslashes

'foo'.match(new RegExp('\\bfoo\\b'));
like image 96
Rian Schmits Avatar answered Sep 20 '22 23:09

Rian Schmits