Hick
Hick

Reputation: 36394

In javascript, how do I match multiple occurrences of a sub string in a string using regex?

I tried using '/bkickstarter/b' but its not able to match with the text like this: I backed this: http://kickstarter.com

Update:

var regex = new RegExp("/\bkickstarter\b/g");
console.log("zach braff's new movie is now being backed on kickstarter: http://www.kickstarter.com/projects/1869987317/wish-i-was-here-1 … also, a documentary on a swartz:  http://www.kickstarter.com/projects/26788492/aaron-swartz-documentary-the-internets-o".match(regex));

That prints a null.

Upvotes: 0

Views: 128

Answers (3)

user2320692
user2320692

Reputation:

The reason var regex = new RegExp("/\bkickstarter\b/g"); doesn't work is because the \ has special meaning in string literal syntax as the start of an escape sequence, so the \ ends up being removed.

To use a \ charater in a string, you need to escape it, which means it'll look like \\, so your final regex

var regex = new RegExp("/\\bkickstarter\\b/g");

Upvotes: 0

Dogbert
Dogbert

Reputation: 222088

You probably wanted to use \b not b.

"I backed this: http://kickstarter.com".match(/\bkickstarter\b/);

If you want to match all occurrences of the regex, add /g modifier.

"I backed this: http://kickstarter.com kickstarter".match(/\bkickstarter\b/g);

Upvotes: 3

Maulik Vora
Maulik Vora

Reputation: 2584

remove /b /b It will search for only separate words, and here you require any string containing 'kickstarter'.

instead put /kickstarter/i for case insensitive search

Upvotes: 0

Related Questions