javascriptanki

Anki - highlight/bold target word in example sentences


In Anki I have a field with the target word {{hanzi}} and a field with some example sentences {{sentch}}. All example sentences contains the target word. What I would like to do is bold the target word in each example sentence. I got it working with the following script but it only bolds out the target word in the first sentence instead of all sentences. Could someone take a look?

<span id="sentch"> {{sentch}} </span>

<script>

var hanzi = '{{hanzi}}';
var sentch = document.getElementById("sentch").innerHTML;
document.getElementById("sentch").innerHTML = sentch 
.replace (hanzi, "<b>" + hanzi + "</b>");

</script>

example sentences


Solution

  • replace by default only replaces the first occurrence if passed a string, and replaceAll may not be supported in the version of javascript used by anki

    Try this instead

    .replace(new RegExp(hanzi, 'g'), "<b>" + hanzi + "</b>");
    

    Using regex and the /g flag will have it search the entire string for replacements.