1

In declaring values we can do:

var x, // comment
    y, // comment
    z; // comment

and that's ok. I have this a little bit longer regExp (I am still introducing myself to regExp) which I am not used to do, which works

var pattern = /^(1\s?)?(\(\d{3}\)|\d{3})[\s\-]?\d{3}[\-\s]?\d{4}$/;

but when I try to do it like I did on my variables declaration example:

var pattern = /^(1\s?)? // optional 1 with space or nonspace; also optional
              (\(\d{3}\)|\d{3}) // optional () bracket in 3 digits
              [\s\-]? // optional space and dash
              \d{3} // 3 digits
              [\-\s]?
              \d{4}$/; // 4 digits

The above code will not work, but I only want to do this for my learning purposes. Is it possible to do?

2 Answers2

1

You could try to build the regular expression, by concatenating an array of strings:

var pattern = new RegExp([
      "(\\(\d{3}\\)|\\d{3})", // optional () bracket in 3 digits
      "[\\s\\-]?", // optional space and dash
      "\\d{3}", // 3 digits
      "[\\-\\s]?",
      "\\d{4}$/" // 4 digits
].join(""));

Of course, this is not very elegant as it requires to escape all those slashes.

Edit: Actualy you can avoid these slash escaping business by creating an array of RegExps instead of strings and then concatenating them:

var pattern = new RegExp([
          /^(1\s?)?/, // optional 1 with space or nonspace; also optional
          /(\(\d{3}\)|\d{3})/, // optional () bracket in 3 digits
          /[\s\-]?/, // optional space and dash
          /\d{3}/, // 3 digits
          /[\-\s]?/,
          /\d{4}$/ // 4 digits
].map(function(x) {return x.source}).join(""));

This need an additional step with map to convert each RegExp back to a string.

theonlygusti
  • 11,032
  • 11
  • 64
  • 119
redneb
  • 21,794
  • 6
  • 42
  • 54
0

Using regex literals you cannot do what you want, what abut trying something like this though:

var pattern = /^(1\s?)?(\(\d{3}\)|\d{3})[\s\-]?\d{3}[\-\s]?\d{4}$/;
/*            /^(1\s?)?                       optional 1 with space or nonspace
              (\(\d{3}\)|\d{3}) optional ()   bracket in 3 digits
              [\s\-]?                         optional space and dash
              \d{3}                           3 digits
              [\-\s]? 
              \d{4}$/                         4 digits
 */

Just add the breakdown underneath? Really though, it is not common to see regexes commented like this, another programmer would be able to analyse the regex themselves if they had to.

Generally commenting why you are doing something, rather than how, is better practice, so adding a comment perhaps for examples of what it should and shouldn't match would be better.

theonlygusti
  • 11,032
  • 11
  • 64
  • 119