Jekyll filter for regex substitution in content?
Asked Answered
P

1

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.

Predict answered 12/9, 2014 at 6:37 Comment(0)
P
18

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)
Predict answered 12/9, 2014 at 6:48 Comment(5)
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.Cyd
@CooperMaruyama don't ever use magic constants if there's a named constant for the same: Regexp::MULTILINE == 4Pusillanimity
Along the same lines, there is also the solution suggested in this GH issue: github.com/Shopify/liquid/issues/202#issuecomment-19112872 (although the solution given here is more complete).Butterball
This will not work in GitHub Pages, unfortunately, as they don't run user plugins for security reasons.Namesake
@CooperMaruyama YOu eman if the section to be replaced could span over multiline than you need the Regexp::MULTILINE ?Alexipharmic

© 2022 - 2024 — McMap. All rights reserved.