skip to Main Content

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


  1. Use document.write() to insert the value of the function after the <script>

    <p>Some text, <script type="text/javascript">document.write(substituteDOI('test'));</script>.</p>
    
    Login or Signup to reply.
  2. Answering..

    I’ll try querySelectorAll, but the issue that jumps to mind is that each <p> element has a different URL for the a href.

    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;

    <script type="text/javascript">
     function substituteDOI(myDOI) {
      return `doi:<a href="${myDOI}">${myDOI}</a>`;
     }
    
     var paragraphs = document.querySelectorAll("p");
     paragraphs.forEach(function(paragraph) {
      var text = paragraph.innerHTML;
      var doiMatch = text.match(/doi:(S+)/);
      if (doiMatch) {
        var doi = doiMatch[1]; // The DOI is the first capturing group
        var newText = text.replace("doi:" + doi, substituteDOI(doi));
        paragraph.innerHTML = newText;
      }
     });
    </script>
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search