I have some HTML representing a bibliography with a few hundred paragraphs, each of which looks like:
<p>Some text, doi:<a href="https://doi.org/some_doi">some_doi</a>.</p>
Currently, I enter the two occurrences of the DOI by hand for each new <p>
entry, but that’s not very efficient, and I’d like to replace with a script to generate the <a href>
for each entry. I can do so using innerHTML
, but that requires generating an id
for each, and a corresponding script in head
, which is even less efficient.
I’ve tried to make a single head
script to replace this workflow:
<script type="text/javascript">
function substituteDOI(myDOI) {
return `doi:<a href="${myDOI}">${myDOI}</a>`;
}
</script>
and calling it inline in body
:
<p>Some text, <script type="text/javascript">substituteDOI('test');</script>.</p>
but that script returns nothing to the <p>
element at all, even when just using return 'test'
, or some similar dummy text. The browser console likewise returns no errors to debug with, and it’s clear that the source itself isn’t being updated. What I’d like is, functionally, an inline way to substitute in a given string (and do some simple concatenation on it).
Is this possible? I realize that using something like a template engine would be more well-suited, but I don’t want to have to rework the entire website page just for this.
2
Answers
Use
document.write()
to insert the value of the function after the<script>
Answering..
Then, you can use a regex to extract the DOI from each paragraph. The regex
/doi:(S+)/
will match the string doi: followed by one or more non-whitespace characters, which should capture the DOI.Example approach;
This approach allows you to replace all DOI’s in your html with a single script, without having to generate an id for each paragraph or a corresponding script in the head. It also avoids the need to rework the entire website page.