Search code examples
javascriptregexperlwhitespacetranspiler

JavaScript regex transpiler?


This question is specifically about a transpiler or transpiler extension. RegExp() is object-creation is massively slower and constructs the RegExp on each iteration.

It seems JavaScript does't permit insensitive whitespace in its regex. Is there any transpiler for JavaScript that permits something like /x from perl, in the Regex.

/x and /xx A single "/x" tells the regular expression parser to ignore most whitespace that is neither backslashed nor within a bracketed character class. You can use this to break up your regular expression into more readable parts. Also, the "#" character is treated as a metacharacter introducing a comment that runs up to the pattern's closing delimiter, or to the end of the current line if the pattern extends onto the next line. Hence, this is very much like an ordinary Perl code comment. (You can include the closing delimiter within the comment only if you precede it with a backslash, so be careful!)

This allows you to write something like

let res = name.match(/^([^\d]*?)(?:\s*[.,]\s*([0-9]+)(?: mo)?)?[.,]?$/);

Like this,

let res = name.match(/
  ^
  ([^\d]*?)                       # name
  (?:\s*[.,]\s*([0-9]+)(?: mo)?)? # age, mo
  [.,]?                           # trailing dirt
  $
 /);

Solution

  • I believe you're looking for something exactly like this: https://www.npmjs.com/package/babel-plugin-transform-modern-regexp