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

Hey @javadalmasi, thanks for sharing this code sample!

I believe I understand the problem is that you’d like to do multiple string replacements on the href attributes of all <a/> and <link/> elements. 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.

If that’s the case, then one simple approach would be to chain additional .replace() calls for each replacement you’d like to make. 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".

I hope this helps!

Thank you very much

1 Like

If we want to change a.com to b.com in the text
I mean, in addition to href, if there is a phrase in the text, replace
for ex
<p> for ex go to <a href="//a.com/some?ga=xxxx"> a.com/some </a> and ......</p>
to
<p> for ex go to <a href="//b.com/some?ga=xxxx"> b.com/some </a> and ......</p>
or
<p> laws of <span>a.com</span>upadted at 2020 </p>
to
<p> laws of <span>b.com</span>upadted at 2020 </p>
How can I do this?