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