简体   繁体   English

多次更换

[英]Multiple replacement

Notice the following code注意下面的代码

async function handleRequest(req) {
  const res = await fetch(req)
  return rewriter.transform(res)
}

 class AttributeRewriter {
  constructor(attributeName) {
    this.attributeName = attributeName
  }

  element(element) {
    const attribute = element.getAttribute(this.attributeName)
    if (attribute) {
      element.setAttribute(
        this.attributeName,
        attribute.replace('/product/', '/p-'),

      )
    }
  }
}

const rewriter = new HTMLRewriter()
  .on('a', new AttributeRewriter('href'))
  .on('link', new AttributeRewriter('href'))



addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

This code works fine Description: I will replace /product/ with /p- with this code Now I'm going to replace these a.com values ​​with b.com and static.a.com with cdn.b.com I'm going to replace them all in this code这段代码工作正常说明:我将用/p-替换/product/这段代码现在我要用b.com替换这些a.com值,用cdn.b.com替换static.a.com我将在此代码中全部替换它们

I believe I understand the problem is that you'd like to do multiple string replacements on the href attributes of all and elements.我相信我理解问题在于您想对 all 和元素的 href 属性进行多个字符串替换。 Specifically, you'd like to replace /product/ with /p and you'd also like to replace a.com with b.com and static.a.com with cdn.b.com.具体来说,您希望将 /product/ 替换为 /p,并且您还希望将 a.com 替换为 b.com,将 static.a.com 替换为 cdn.b.com。

If that's the case, then one simple approach would be to chain additional .replace() calls for each replacement you'd like to make.如果是这种情况,那么一种简单的方法是为您想要进行的每个替换链接额外的 .replace() 调用。 For example, something like this might work:例如,这样的事情可能会奏效:

element.setAttribute(
  this.attributeName,
  attribute
    .replace('/product/', '/p-')
    .replace('//a.com/', '//b.com/')
    .replace('//static.a.com/', '//cdn.b.com/')
)

With this code, href="http://a.com/product/name" would be replaced with href="http://b.com/p-name".使用此代码, href="http://a.com/product/name" 将替换为 href="http://b.com/p-name"。

I hope this helps!我希望这有帮助! https://community.cloudflare.com/t/multiple-replacement/152668/2 https://community.cloudflare.com/t/multiple-replacement/152668/2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM