javascripthtmlanki

Loop through HTML and replace strings with javascript and Regex


I have this HTML in Anki:

<p>[!Quote] Title of callout 1<br>Content of callout 1</p>
<p>[!Quote] Title of callout 2<br>Content of callout 2</p>
<p>[!Quote] Title of callout 3<br>Content of callout 3</p>

And want it to look like this:

<p><b>Title of callout 1</b><br>Content of callout 1</p>
<p><b>Title of callout 2</b><br>Content of callout 2</p>
<p><b>Title of callout 3</b><br>Content of callout 3</p>

So I want to remove [!Quote] and make Title of callout bold. I came up with this javascript code:

var quoteRegex = /<p>\[!Quote].*(?=<br>)/g;
var title = /(?<=\[!Quote]\s).*(?=<br>)/g;
var back = document.getElementById('back'); // Backside of flashcard containing the paragraphs
var titleString = back.innerHTML.match(title);
back.innerHTML = back.innerHTML.replace(quoteRegex, '<b>' + titleString + '</b>');

But got stuck there, because titleString matches all titles and separates them with a comma, hence causes something like this when I tried back.innerHTML.replace:

<p><b>Title of callout 1, Title of callout 2, Title of callout 3</b><br>Content of callout 1</p>

Therefore I think I need to loop through the paragraphs so I can replace the titles one by one, but I have no idea how to get that done. Thanks in advance for your help!


Solution

  • Use a capture group reference:

    const html = `<p>[!Quote] Title of callout 1<br>Content of callout 1</p>
    <p>[!Quote] Title of callout 2<br>Content of callout 2</p>
    <p>[!Quote] Title of callout 3<br>Content of callout 3</p>`;
    
    $div.innerHTML = html.replace(/\[\!Quote\]\s*(.*?)<br>/g, '<b>$1</b><br>');
    <div id="$div"></div>