Convert Ruby Regexp to JavaScript RegExp

converse
Brian Cardarella

CEO & Founder

Brian Cardarella

This has a very limited use case, but I needed it for ClientSideValidations. It took a while to track down some of the possible conversion issues, I figure someone else might find this useful.

class Regexp
  def to_javascript
    Regexp.new(inspect.sub('\\A','^').sub('\\Z','$').sub('\\z','$').sub(/^\//,'').sub(/\/[a-z]*$/,'').gsub(/\(\?#.+\)/, '').gsub(/\(\?-\w+:/,'('), self.options).inspect
  end
end

When you render it to the client simply instantiate a new RegExp object with the resulting string:

new RegExp(regexpStringFromRuby);

If there are any edge-cases that won’t convert cleanly please report them in the comments.

See how it is being used in ClientSideValidations to_json tests cases

Newsletter

Stay in the Know

Get the latest news and insights on Elixir, Phoenix, machine learning, product strategy, and more—delivered straight to your inbox.

Narwin holding a press release sheet while opening the DockYard brand kit box