10

Is there a Jekyll filter that will replace text using a regular expression (regex) filter?

I believe the "built-in" filter replace does simple string substitution.

barfuin
  • 16,865
  • 10
  • 85
  • 132
sameers
  • 4,855
  • 3
  • 35
  • 44

1 Answers1

17

In the event there isn't a (better) solution, I'll throw in the very obviously simple plugin that will do the trick - drop this into your _plugins/ folder as the file regex_filter.rb - it takes the regex as a string, as the first arg, and the replacement as the second arg (for example, {{ page.url | replace_regex: '/$', '' }}:

module Jekyll
  module RegexFilter
    def replace_regex(input, reg_str, repl_str)
      re = Regexp.new reg_str

      # This will be returned
      input.gsub re, repl_str
    end
  end
end

Liquid::Template.register_filter(Jekyll::RegexFilter)
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
sameers
  • 4,855
  • 3
  • 35
  • 44
  • If you're using this for replacing HTML, make sure to change `re = Regexp.new reg_str` to `re = Regexp.new reg_str, 4` so that it matches multiple lines. – Cooper Maruyama Mar 04 '15 at 05:55
  • 4
    @CooperMaruyama don't ever use magic constants if there's a named constant for the same: [`Regexp::MULTILINE`](http://ruby-doc.org/core-2.2.0/Regexp.html#constants-list) == [`4`](http://ruby-doc.org/core-2.2.0/Regexp.html#options-method) – TWiStErRob Jul 27 '15 at 10:03
  • Along the same lines, there is also the solution suggested in this GH issue: https://github.com/Shopify/liquid/issues/202#issuecomment-19112872 (although the solution given here is more complete). – Patrice Chalin Nov 17 '16 at 19:22
  • 3
    This will not work in GitHub Pages, unfortunately, as they don't run user plugins for security reasons. – barfuin Nov 03 '17 at 17:51
  • @CooperMaruyama YOu eman if the section to be replaced could span over multiline than you need the `Regexp::MULTILINE` ? – Csaba Toth May 28 '20 at 22:22