Skip to content

Instantly share code, notes, and snippets.

@jgodson
Created June 21, 2020 15:24
Show Gist options
  • Save jgodson/250aa16a3033c4bbf5a128676a5ab30f to your computer and use it in GitHub Desktop.
Save jgodson/250aa16a3033c4bbf5a128676a5ab30f to your computer and use it in GitHub Desktop.
JavaScript function to replace liquid args in a string with the given replacements
function replaceLiquid(string, replacements) {
  if (typeof replacements === 'string') {
    replacements = [replacements];
  }
  var regex = /{% raw %}({{\s*[\w\.]+\s*}}){% endraw %}/;
  var match = regex.exec(string);
  var index = 0;
  while (match) {
    if (replacements[index]) {
      string = string.replace(match[0], replacements[index]);
    } else {
      break;
    }
    index++;
    match = regex.exec(string);
  }
  return string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment