skip to Main Content

I have an HTML file with a list of documents. The file names contain information about the author and the publication year. In the following style: "Document title -a Author name -j Publication year.pdf" I want the author name to be automatically coloured blue and the publication year green. I think this will require javascript, inserted in the HTML header. The javascript would have to ensure that the text between "-a" and "-j" and between "-j" and "." is coloured accordingly. For example, by automatically inserting a span class "author" and a span class "year", for which CSS instructions are contained in the style area of the header. However, I don’t know how to write such a Java script. Can anyone help me?

Here is an example of the html file. HTML works, but but the Javascript is missing:

.filename {
  margin-left: 4em;
}

.author {
  color: blue;
}

.year {
  color: green;
}
<span class=filename>My document -a Michael Singer -j 2023.pdf</span> <span class=filename>My document -a Michael Jackson -j 2008.pdf</span> <span class=filename>My document -a John Washington -j 2014.pdf</span>

5

Answers


  1. Chosen as BEST ANSWER

    Thanks @adamoadamo, that works. (And also thanks to all other contributors.) I would like to make the color highlighting work even if a document is named only by publication date or only by author. So I tried to insert the javascript multiple times, specifically for the year (start: "-j", end: ".") and specifically for the author (start: "-a", end: "-" or "."). But then only the last javascript in the header is applied. How can I solve this? This was my try:

    <head>
    <style>
    .filename { margin-left: 4em;}
    .author { color: blue;}
    .year { color: green;}
    </style>
    <script>
    window.onload = function() {
      document.querySelectorAll('.dateiname').forEach((elem) => {
        const text = elem.textContent;
        const newHtml = text.replace(/-a (.*?)-/, 
                                     '-a <span class="author">$1</span>-');
        elem.innerHTML = newHtml;
      });
    };
    
    window.onload = function() {
      document.querySelectorAll('.dateiname').forEach((elem) => {
        const text = elem.textContent;
        const newHtml = text.replace(/-a (.*?)./, 
                                     '-a <span class="author">$1</span>.');
        elem.innerHTML = newHtml;
      });
    };
    
    window.onload = function() {
      document.querySelectorAll('.dateiname').forEach((elem) => {
        const text = elem.textContent;
        const newHtml = text.replace(/-j (.*?)./, 
                                     '-j <span class="year">$1</span>.');
        elem.innerHTML = newHtml;
      });
    };
    </script>
    </head>
    <body>
    <span class=filename>My document -a Michael Singer -j 2023.pdf</span>
    <span class=filename>My document -j 2008.pdf</span>
    <span class=filename>My document -a John Washington.pdf</span>
    </body>
    

  2. You could use String#replace on the innerHTML of each span.

    document.querySelectorAll('.filename').forEach(s => 
      s.innerHTML = s.innerHTML.replace(/(?<=-a )(.+?) -j (.+?)(?=.)/, 
         (_, g1, g2) => `<span class=author>${g1}</span> -j <span class=year>${g2}</span>`));
    .filename {
      margin-left: 4em;
    }
    
    .author {
      color: blue;
    }
    
    .year {
      color: green;
    }
    <span class=filename>My document -a Michael Singer -j 2023.pdf</span> <span class=filename>My document -a Michael Jackson -j 2008.pdf</span> <span class=filename>My document -a John Washington -j 2014.pdf</span>
    Login or Signup to reply.
  3. You could achieve this with JavaScript by searching for the patterns "-a" and "-j" in each filename and wrapping the corresponding text segments in spans with the appropriate classes.

    The CSS classes in your style section (as you have it):

    <style>
    .filename {
      margin-left: 4em;
    }
    
    .author {
      color: blue;
    }
    
    .year {
      color: green;
    }
    </style>
    

    In your JavaScript section, you can select all elements with the class "filename", and then use regular expressions to identify and style the author name and publication year as per your requirement:

    <script>
    window.onload = function() {
      document.querySelectorAll('.filename').forEach((elem) => {
        const text = elem.textContent;
        const newHtml = text.replace(/-a (.*?) -j (.*?).pdf/, 
                                     '-a <span class="author">$1</span> -j <span class="year">$2</span>.pdf');
        elem.innerHTML = newHtml;
      });
    };
    </script>
    

    And then your HTML should be fine as you have it:

    <span class="filename">My document -a Michael Singer -j 2023.pdf</span>
    <span class="filename">My document -a Michael Jackson -j 2008.pdf</span>
    <span class="filename">My document -a John Washington -j 2014.pdf</span>
    
    Login or Signup to reply.
  4. The previous answers are good enough to solve your case. I will let here my solution as an alternative, since I am not a big fan on manipulating the inner html.

    The procedures are:

    1. Capture all the "filename" elements on the page;
    2. Use a regex pattern to identify the author and year flags;
    3. Split the filename to get each part of the text;
    4. If the part starts with a -, create a flag element with its appropriate class name, else just create a text node.
    5. Clean the current html from the "filename" element
    6. Recreate the "filename" content with the new nodes.
    const filenames = document.querySelectorAll('.filename')
    
    function createFlagElement(text) {
      const flagContainer = document.createElement('span')
      const flag = document.createTextNode(text.substring(0, 3))
      const flagElement = document.createElement('span')
      flagElement.innerText = text.substring(3)
      flagContainer.appendChild(flag)
      flagContainer.appendChild(flagElement)
      if (text.startsWith('-a')) {
        flagElement.classList.add('author')
      }
      if (text.startsWith('-j')) {
        flagElement.classList.add('year')
      }
      return flagContainer
    }
    
    function createNodes(splittedName) {
      const nodes = splittedName.map((text) => {
        if (text.startsWith('-')) return createFlagElement(text)
        return document.createTextNode(text)
      })
      return nodes
    }
    
    function highlightFlags(filename, nodes) {
      filename.innerHTML = ''
      for (const node of nodes) {
        filename.appendChild(node)
      }
    }
    
    for (const filename of filenames) {
      const flagPatterns = /(-a w+s?w+)|(-j w+)/g
      const splittedName = filename.innerText.split(flagPatterns).filter(Boolean)
      const nodes = createNodes(splittedName)
      highlightFlags(filename, nodes)
    }
    .filename {
      margin-left: 4em;
    }
    
    .author {
      color: blue;
    }
    
    .year {
      color: green;
    }
    <span class=filename>My document -a Michael Singer -j 2023.pdf</span> <span class=filename>My document -a Michael Jackson -j 2008.pdf</span> <span class=filename>My document -a John Washington -j 2014.pdf</span>
    Login or Signup to reply.
  5. document.querySelectorAll('.filename').forEach((item) => {
            const titleParts = item.textContent.split('-a');
            if (titleParts.length === 2) {
                const authorParts = titleParts[1].split('-j');
                if (authorParts.length === 2) {
                    const authorName = authorParts[0].trim();
                    const year = authorParts[1].replace('.pdf', '').trim();
    
                    item.innerHTML = `${titleParts[0]} -a <span class="author">${authorName}</span> -j <span class="year">${year}</span>.pdf`;
                }
            }
        });
    .filename {
      margin-left: 4em;
    }
    
    .author {
      color: blue;
    }
    
    .year {
      color: green;
    }
    <span class="filename">My document 1 -a Chris Drake -j 2021.pdf</span>
    <span class="filename">My document 2 -a Darcie Daniel -j 2011.pdf</span>
    <span class="filename">My document 3 -a Yasmin Russo -j 2023.pdf</span>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search