Skip to content

Converts Ruby regexes to JavaScript regexes.

License

Notifications You must be signed in to change notification settings

jaynetics/js_regex

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

JsRegex

Gem Version Build Status Build Status Coverage

This is a Ruby gem that translates Ruby's regular expressions to various JavaScript flavors.

It can handle almost all of Ruby's regex features, unlike a search-and-replace approach. If any incompatibilities remain, it returns helpful warnings to indicate them.

Installation

Add it to your gemfile or run

gem install js_regex

Usage

Basic usage

In Ruby:

require 'js_regex'

ruby_hex_regex = /0x\h+/i

js_regex = JsRegex.new(ruby_hex_regex)

js_regex.warnings # => []
js_regex.source # => '0x[0-9A-F]+'
js_regex.options # => 'i'

To inject the result directly into JavaScript, use #to_s or String interpolation. E.g. in inline JavaScript in HAML or SLIM you can simply do:

var regExp = #{js_regex};

Use #to_json if you want to send it as JSON or #to_h to include it as a data attribute of a DOM element.

render json: js_regex

js_regex.to_h # => { source: '[0-9A-F]+', options: 'i' }

To turn the data attribute or parsed JSON back into a RegExp in JavaScript, use the new RegExp() constructor:

var regExp = new RegExp(jsonObj.source, jsonObj.options);

Heed the Warnings

You might have noticed the empty warnings array in the example above:

js_regex = JsRegex.new(ruby_hex_regex)
js_regex.warnings # => []

If this array isn't empty, that means that your Ruby regex contained some stuff that can't be carried over to JavaScript. You can still use the result, but this is not recommended. Most likely it won't match the same strings as your Ruby regex.

advanced_ruby_regex = /(?<!fizz)buzz/

js_regex = JsRegex.new(advanced_ruby_regex)
js_regex.warnings # => ["Dropped unsupported negated lookbehind '(?<!fizz)' at index 0 (requires at least `target: 'ES2018'`)"]
js_regex.source # => 'buzz'

There is also a strict initializer, JsRegex::new!, which raises a JsRegex::Error if there are incompatibilites. This is particularly useful if you use JsRegex to convert regex-like strings, e.g. strings entered by users, as a JsRegex::Error might also occur if the given regex is invalid:

begin
  user_input = '('
  JsRegex.new(user_input)
rescue JsRegex::Error => e
  e.message # => "Premature end of pattern (missing group closing parenthesis)"
end

Modifying RegExp options/flags

An options: argument lets you append options (a.k.a. "flags") to the output:

JsRegex.new(/x/i, options: 'g').to_h
# => { source: 'x', options: 'gi' }

Set the g flag like this if you want to use the regex to find or replace multiple matches per string.

Converting for modern JavaScript

A target: argument can be given to target more recent versions of JS and unlock extra features or nicer output. 'ES2009' is the default target. 'ES2015' and 'ES2018' are also available.

# ES2015 and greater use the u-flag to avoid lengthy escape sequences
JsRegex.new(/πŸ˜‹/, target: 'ES2009').to_s # => "/(?:\\uD83D\\uDE0B)/"
JsRegex.new(/πŸ˜‹/, target: 'ES2015').to_s # => "/πŸ˜‹/u"
JsRegex.new(/πŸ˜‹/, target: 'ES2018').to_s # => "/πŸ˜‹/u"

# ES2018 adds support for lookbehinds, properties etc.
JsRegex.new(/foo\K\p{ascii}/, target: 'ES2015').to_s # => "/foo[\x00-\x7f]/"
JsRegex.new(/foo\K\p{ascii}/, target: 'ES2018').to_s # => "/(?<=foo)\p{ASCII}/"

Supported Features

These are the supported features by target.

Unsupported features are at the bottom of this list.

When converting a Regexp that contains unsupported features, corresponding parts of the pattern are dropped from the result and warnings are emitted.

Description Example ES2009 ES2015 ES2018
anchors \A, \z, ^, $ βœ“ [6] βœ“ [6] βœ“
escaped meta chars \\A βœ“ βœ“ βœ“
dot matching astral chars /./ =~ 'πŸ˜‹' βœ“ βœ“ βœ“
Ruby's multiline mode [1] /.+/m βœ“ βœ“ βœ“
Ruby's free-spacing mode / http (s?) /x βœ“ βœ“ βœ“
possessive quantifiers [2] ++, *+, ?+ βœ“ βœ“ βœ“
atomic groups [2] a(?>bc|b)c βœ“ βœ“ βœ“
conditionals [2] (?('a')b|c) βœ“ βœ“ βœ“
option groups/switches (?i-m:..), (?x).. βœ“ βœ“ βœ“
local encoding options (?u:\w) βœ“ βœ“ βœ“
absence groups /\*(?~\*/)\*/ βœ“ βœ“ βœ“
chained quantifiers /A{2}{4}/ =~ 'A' * 8 βœ“ βœ“ βœ“
hex types \h and \H \H\h{6} βœ“ βœ“ βœ“
bell and escape shortcuts \a, \e βœ“ βœ“ βœ“
all literals, including \n eval("/\n/") βœ“ βœ“ βœ“
newline-ready anchor \Z last word\Z βœ“ βœ“ βœ“
generic linebreak \R data.split(/\R/) βœ“ βœ“ βœ“
meta and control escapes /\M-\C-X/ βœ“ βœ“ βœ“
numeric backreferences \1, \k<1> βœ“ βœ“ βœ“
relative backreferences \k<-1> βœ“ βœ“ βœ“
named backreferences \k<foo> βœ“ βœ“ βœ“
numeric subexp calls \g<1> βœ“ βœ“ βœ“
relative subexp calls \g<-1> βœ“ βœ“ βœ“
named subexp calls \g<foo> βœ“ βœ“ βœ“
recursive subexp calls [3] \g<0> βœ“ βœ“ βœ“
nested sets [a-z[A-Z]] βœ“ βœ“ βœ“
types in sets [a-z\h] βœ“ βœ“ βœ“
properties in sets [a-z\p{sc}] βœ“ βœ“ βœ“
set intersections [\w&&[^a]] βœ“ βœ“ βœ“
recursive set negation [^a[^b]] βœ“ βœ“ βœ“
posix types [[:alpha:]] βœ“ βœ“ βœ“
posix negations [[:^alpha:]] βœ“ βœ“ βœ“
codepoint lists \u{61 63 1F601} βœ“ βœ“ βœ“
unicode properties \p{Dash}, \p{Thai} βœ“ βœ“ βœ“
unicode abbreviations \p{Mong}, \p{Sc} βœ“ βœ“ βœ“
unicode negations \p{^L}, \P{L} βœ“ βœ“ βœ“
astral plane properties [2] \p{emoji} βœ“ βœ“ βœ“
astral plane literals [2] 😁 βœ“ βœ“ βœ“
astral plane ranges [2] [😁-😲] βœ“ βœ“ βœ“
capturing group names [4] (?<a>, (?'a' X X βœ“
extended grapheme type \X X X βœ“
lookbehinds (?<=a), (?<!a) X X βœ“
keep marks \K X X βœ“
sane word boundaries \b, \B X [5] X [5] βœ“
nested keep mark /a(b\Kc)d/ X X X
backref by recursion level \k<1+1> X X X
previous match anchor \G X X X
variable length absence (?~(a+|bar)) X X X
comment groups [4] (?#comment) X X X
inline comments [4] /[a-z] # comment/x X X X

[1] Keep in mind that Ruby's multiline mode is more of a "dot-all mode" and totally different from JavaScript's multiline mode.

[2] See here for information about how this is achieved.

[3] Limited to 5 levels of depth.

[4] These are dropped without warning because they can be removed without affecting the matching behavior.

[5] When targetting ES2018, \b and \B are replaced with a lookbehind/lookahead solution. For other targets, they are carried over as is, but generate a warning. They only recognize ASCII word chars in JavaScript, and neither the u nor the v flag makes them behave correctly.

[6] ^ only matches at the beginning of the string for the targets ES2009 and ES2015. See #30

How it Works

JsRegex uses the gem regexp_parser to parse a Ruby Regexp.

It traverses the AST returned by regexp_parser depth-first, and converts it to its own tree of equivalent JavaScript RegExp tokens, marking some nodes for treatment in a second pass.

The second pass then carries out all modifications that require knowledge of the complete tree.

After the second pass, JsRegex flat-maps the final tree into a new source string.

Many Regexp tokens work in JavaScript just as they do in Ruby, or allow for a straightforward replacement, but some conversions are a little more involved.

Atomic groups and possessive quantifiers are missing in JavaScript, so the only way to emulate their behavior is by substituting them with backreferenced lookahead groups.

Astral plane characters convert to ranges of surrogate pairs when targetting ES2009 (which doesn't support astral plane chars).

Properties and posix classes expand to equivalent character sets, or surrogate pair alternations if necessary. The gem regexp_property_values helps by reading out their codepoints from Onigmo.

Character sets a.k.a. bracket expressions offer many more features in Ruby compared to JavaScript. To work around this, JsRegex calls on the gem character_set to calculate the matched codepoints of the whole set and build a completely new set string for all except the most simple cases.

Conditionals expand to equivalent alternations in the second pass, e.g. (<)?foo(?(1)>) expands to (?:<foo>|foo) (simplified example).

Subexpression calls are replaced with the conversion result of their target, e.g. (.{3})\g<1> expands to (.{3})(.{3}).

The tricky bit here is that these expressions may be nested, and that their expansions may increase the capturing group count. This means that any following backreferences need an update. E.g. (.{3})\g<1>(.)\2 (which matches strings like "FooBarXX") converts to (.{3})(.{3})(.)\3.

Contributions

Feel free to send suggestions, point out issues, or submit pull requests.

Outlook

The gem is pretty feature-complete at this point. The remaining unsupported features listed above are either impossible or impractical to replicate in JavaScript. The generated output could still be made more concise in some cases, through usage of the newer s or v flags. Finally, ES2018 might become the default target at some point.

Similar projects

  • Oniguruma-To-ES is an Oniguruma to JavaScript regex transpiler, written in JavaScript. Please note that it is not fully compatible with Ruby regexes as Ruby uses Onigmo, a fork of Oniguruma.
  • regex-translator is a regex transpiler written in JavaScript that covers various formats, not including Ruby.