String#js_replace

This page was written in response to James Coglan’s Emulating JavaScript’s String#replace in Ruby. Here’s a better implementation of the same idea using Ruby’s built-in MatchData class:

class String
  def js_replace(pattern, &block)
    gsub(pattern) do |_|
      md = Regexp.last_match
      args = [md.to_s, md.captures, md.begin(0), self].flatten
      block.call(*args)
    end
  end
end