regex JavaScript正则表达式多行替换

q35jwt9p  于 2023-08-08  发布在  Java
关注(0)|答案(1)|浏览(103)

我想把这个换掉

@#@ visibility="hidden" @#@
{% include "grid-overlay.njk" %}

@#@ contentPartial="promo/tru-report/"
class="q-promo-container promo--hidden"
expires="2023-04-30T17:00:00Z"@#@
{% include "promo-banner.njk" %}

字符串
用这个

{% set visibility="hidden" %}
{% include "grid-overlay.njk" %}

{% set contentPartial="promo/tru-report/" %}
{% set class="q-promo-container promo--hidden" %}
{% set expires="2023-04-30T17:00:00Z" %}
{% include "promo-banner.njk" %}


我可以用这个正则表达式找到所有匹配项

regex = /@#@\s*([a-zA-Z0-9-_/\.=:"'\s]+)\s*@#@/gim;


但是我不知道如何使用replace函数来获得所需的输出。有什么建议吗?

q5iwbnjs

q5iwbnjs1#

算了,我用一个替换函数算出来的。

function replacer(match, p1, offset, string) {
  var variablesArray = p1.split(/"\s+/gi);
  variablesArray = variablesArray.filter(n => n);
  var statements = variablesArray.map(function (statement) {
    return `{% set ${statement}" %}`;
  });
  statements = statements.join("\n");
  return statements;
}

oldContent = newContent;
regex = /@#@\s*([a-zA-Z0-9-_/\.=:"'\s]+)\s*@#@/gim;
newContent = oldContent.replace(regex, replacer);

字符串

相关问题