1

Background: I used quill.js to get some rich text input. The result I want is quite similar to HTML so I went with the quill.container.firstChild.innerHTML approach instead of actually serializing the data. But when it comes to anchor, instead of

<a href="test.html">Anchor</a>

I actually want

Anchor{{link:test.html}}

With .replace() method I easily got {{link:test.html}}Anchor</a> but I need to put the link description after the Anchor text. Is there a way to swap {{link:test.html}} with the next </a> so I can get the desired result? There can be multiple anchors in the string, like:

str = 'This is a <a href="test1.html">test</a>. And <a href="test2.html">another one</a> here.'

I would like it to become:

str = 'This is a test{{link:test1.html}}. And another one{{link:test2.html}} here.'
Uwe Keim
  • 38,279
  • 56
  • 171
  • 280
Agustín Dorado
  • 254
  • 1
  • 9

2 Answers2

4

You could also use dom methods. The dom is a better html parser than regex. This is a fairly simple replaceWith

str = 'This is a <a href="test1.html">test</a>. And <a href="test2.html">another one</a> here.'

var div = document.createElement('div');
div.innerHTML = str;
div.querySelectorAll('a').forEach(a=>{
    a.replaceWith(`${a.textContent}{{link:${a.getAttribute('href')}}}`)
})

console.log(div.innerHTML)
charlietfl
  • 169,044
  • 13
  • 113
  • 146
2

Yes, you can use capture groups and placeholders in the replacement string, provided it really is in exactly the format you've shown:

const str = 'This is a <a href="test1.html">test</a>. And <a href="test2.html">another one</a> here.';
const result = str.replace(/<a href="([^"]+)">([^<]+)<\/a>/g, "$2{{link:$1}}");
console.log(result);

This is very fragile, which is why famously you don't use regular expressions to parse HTML. For instance, it would fail with this input string:

const str = 'This is a <a href="test1.html">test <span>blah</span></a>. And <a href="test2.html">another one</a> here.';

...because of the <span>blah</span>.

But if the format is as simple and consistent as you appear to be getting from quill.js, you can apply a regular expression to it.

That said, if you're doing this on a browser or otherwise have a DOM parser available to you, use the DOM as charlietfl demonstrates;

T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769