Jekyll filter for replacing regular expressions in content?

Is there a Jekyll filter that replaces text using a regex filter?

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

+8
jekyll liquid jekyll-extensions
source share
2 answers

In case there is no (better) solution, I will throw a very obvious simple plugin that will do the trick - put this in your _plugins/ folder as regex_filter.rb file - it takes 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) 
+11
source share

As stated in the Jekyll documentation (but very easy to miss):

Jekyll uses the Liquid template language to process templates. All standard Liquid tags and filters are supported.

Therefore, you can use (as indicated in the Liquid documentation )

  replace 

eg.

  replace - replace each occurrence eg {{ 'foofoo' | replace:'foo','bar' }} #=> 'barbar' 

No need to add an additional plugin!

Hooray!

-3
source share

All Articles