0

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
  $
 /);
9
  • Updated the question: This question is specifically about a transpiler or transpiler extension. RegExp() is object-creation is massively slower and constructs the RegExp on each iteration. Commented Dec 16, 2018 at 22:14
  • 1
    Just use the JS equivalent of Perl's state re = qr/.../;, which would be something along the lines of persistent_var ||= new RegExp(...);. Commented Dec 16, 2018 at 22:20
  • If you're specifically asking for a tool, then this is off topic anyway. Commented Dec 16, 2018 at 22:29
  • @ikegami that incurs a runtime compilation cost every time the pattern is encountered which is pretty substantial. Commented Dec 16, 2018 at 22:31
  • No, the cost only occurs once. Commented Dec 16, 2018 at 22:32

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.