@bluefrog was a lot faster than me, but I will still respond to your original questions and comment on your code.
You’re talking about a MD document here, right?
What is “this” here? The string “ACTION”? The document? Something else entirely?
It is, if you’re using the most recent version of DT.
You do not reference the MD, because JavaScript is not executed in the context of MD. There’s no DOM for MD, only for HTML. And this DOM only exists in a user agent, aka browser (or the Webkit preview available in DT). Long story short: check out Mozilla Developer Network for all the gory details.
Your code might in fact be ok (syntactically), but semantically it doesn’t make much sense. The replace
method does not change the original string (fortunately), but returns a new one. So html.replace
does nothing at all.
Secondly, why are you using a function as a second parameter to the replace
call? That’s kind of over the top if you want to simply replace a string.
What you could try:
const term = "ACTION";
const RE = new RegExp("ACTION", "gi");
const html = document.innerHTML;
document.innerHTML = html.replaceAll(RE, `<mark>${term}</mark>`);
Also, why do you use the “i” modifier in the RE, if you only want to highlight “ACTION” (but possibly not “action” nor “re_action_” or “trans_action_”
Which leads me to: If you’re looking for the single word ACTION, you should say so. In which case using a RE makes sense again, as in
new RegExp(`\b${term}\b`, "g")
Also, using document.innerHTML
seems way to generous. I suppose that your term
occurs only in normal text, i.e. inside paragraphs. So you could do something like
const paras = document.getElementsByTagName('p');
paras.forEach( p => {
... work on the ACTION stuff here ...
})
That makes the whole enterprise a lot safer, since you do not risk to (e.g.) modify the word “ACTION” in the head
element or somewhere else.
Finally, I’d never have a JS function like that sit around in the HTML. Rather, install it as a DOMContentLoaded
handler. Then it will only be run when the DOM is already available. If you just put it into the HTML like here, the user agent will run it as soon as it sees the function. Which is probably before the DOM is even available, making it simply fail.
There’s one example for that here Code highlighting in Markdown documents - #4 by chrillek
and another, more geared towards what you’re doing, here CSS für Devonthink - #13 by chrillek
(the text is in German, the code is not)