learningjavascriptks learningjavascriptks - 3 months ago 9
Javascript Question

How to add a comment inside a regexp value or value?

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 intoducing 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 wanna do this for my learning purposes. Is it possible to do?

Answer

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.