user606521
user606521

Reputation: 15434

Javascript regex created from string - why it does not work?

My string is:

...
abc {
   color: red;
   border-color: black;
}
...

I would like to match (replace) everything between curly braces. I managed to write working regexp like this:

/\{[.\s\w:;-]*\}/ig

But I need to create regexp from string and it does not work:

new RegExp("{[.\s\w:;-]*}","ig"); // does not work

Everything is on fiddle: http://jsfiddle.net/3ru18Lj9/

Upvotes: 0

Views: 63

Answers (3)

Khaleel
Khaleel

Reputation: 1371

Check this updated fiddle.

You have to escape the slashes . tats it

new RegExp("{[.\\s\\w:;-]*}","ig");

http://jsfiddle.net/khaleel/3ru18Lj9/2/

Upvotes: 1

Mike Samuel
Mike Samuel

Reputation: 120506

\s in a regexp means something special but \s in a string is the same as just s.

You need to escape the \, so that the regular expression parser sees it.

new RegExp("\\{[.\\s\\w:;-]*\\}","ig");

Upvotes: 2

anubhava
anubhava

Reputation: 785088

You can use:

var re = new RegExp("\\{[\\S\\s]*\\}", "g");

to match newlines as well in JS.

  • You must use \\ (double escaping) while constructing RegExp object.
  • Since JS doesn't have s (DOTALL) flag use [\S\s] to match all characters including newlines.

PS: However remember that it won't handle nested braces.

Upvotes: 4

Related Questions