Kuba T
Kuba T

Reputation: 3083

JavaScript regular expressions written in several lines

I've got some problem with javascript coding style. Due to Google Closure Linter, lines should be no longer than 80 characters, but I've got some regexp which is circa 120 characters long. When I break line in the middle of regexp it doesn't work properly. How to handle that?

var pattern = /veeery, veeeery looooooooooooooooooong regular expressssssssssssssssssssssssssion/;

Upvotes: 0

Views: 112

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382150

A solution would be to do this :

var pattern = new RegExp(
   'veeery, veeeery looooooooooooooooooong'
   +' regular expressssssssssssssssssssssssssion'
);

If your pattern declaration was in a loop, which is fine for a regex literal, I'd recommend to move this declaration before the loop, to avoid to repeat the cost of creating the instance and compiling it.

Be careful to the escape sequences, you'll have to replace \ with \\ : the two following regexes are identical

/\d/g
new RegExp("\\d", 'g')

Upvotes: 4

Pointy
Pointy

Reputation: 413709

Though I think that's a ridiculous rule for a linter, the solution would be to create the regular expression from a string expression.

var regex = new RegExp(
  "first part of long regex" +
  "second part of long regex" +
  "and so on"
);

You'll have to double-escape escaped metacharacters in the regular expression. That is, if your native-style regex was:

var regex = /swing on a \*/;

then your string would need to be:

var regex = new RegExp("swing on a \\*");

Upvotes: 0

Related Questions