skip to Main Content

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!

2

Answers


  1. There’s an another approach with regex. Match [!Quote] and replace it instead of lookbehind.

    const regex = /(?<quote>[!Quote]s)(?<title>.*)(?=<br>)/g;
    
    // Alternative syntax using RegExp constructor
    // const regex = new RegExp('(?<quote>\[!Quote]\s)(?<title>.*)(?=<br>)', 'g')
    
    const back = document.getElementById('back');
    const subst = `<b>${title}</b>`;
    
    // The substituted value will be contained in the result variable
    back.innerHTML = = back.innerHTML.replace(regex, subst);
    
    
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search