JavaScript Regex formatted on multiple lines

Issue

I have a really complex JavaScript replace regex function and I am wondering is there a way to format the regex code on multiple lines like this:

/
(
    ([0-9]{1,2})
    (\/|\.)
    ([0-9]{1,2})
    (\/|\.)
    ([0-9]{2,4})\s
)?
([0-9]{1,2})
:
([0-9]{1,2})
(
    (:|\s)
    ([0-9]{1,2})
)?
/ig

Also I’d like to ask if there is another way to format regex so it’s easier to read.

Solution

JavaScript doesn’t have support for the /x flag (which allows spaces and comments), but you can split your expression over multiple lines using strings. For example:

var re = new RegExp(
     "foo" +
     "bar" +
     "baz",
     "ig");

Of course this has the disadvantage of regular string quoting of regex (double escapes).

You could also use XRegExp with its (?x) flag, but you are still limited by the regular JS string quoting.

Answered By – Qtax

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published