As far as I know, field references inside scripts don’t work. You can wrap {{gender}} in a tag and in the script, retrieve the tag’s content instead of trying to reference the field.
Thank you for your answer.
I’m not sure if I understood correctly.
The field reference {{gender}} seems to work in this code.
The output of the variable genderTerm1 and genderTerm2 are in both cases “feminin”.
The output of the variable image_source_regex1 is: img src=‘feminin.jpg’
The value of {{gender}} is parsed correctly.
But as soon as I wrap the code with < >, it results in an broken image url.
Sorry, I don’t use JavaScript often in Anki and got it backwards. You can’t modify field references because they will already be replaced. So just ignore what I wrote.
As for your problem, that’s strange. I mean, you can just replace
var image_source_regex2 = genderTerm2.replace(/(.+$)/g, "<img src='$1.jpg'>");
with
var image_source_regex2 = "<" + genderTerm2.replace(/(.+$)/g, "img src='$1.jpg'") + ">";
But I have no idea why this is necessary.
var image_source_regex2 =genderTerm2.replace(/(.+$)/g, "<" + "img src='$1.jpg'" + ">");
also works, so the problem is somehow with the literal tag quote.
This is the answer I’ve got from ssnoyes on reddit:
It looks like Anki is parsing the note; special characters inside angle brackets get HTML encoded, so your "<img src='$1.jpg'>" is being encoded into "<img src='%241.jpg'>" (because %24 is the HTML encoding for the ‘$’ character).
That makes sense. So JS doesn’t see a backreference because Anki encoded the $ and replaces with the literal string. The image reference is evaluated after decoding, so Anki then searches for the image $1.jpg.