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
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:
You could use
String#replace
on theinnerHTML
of each span.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):
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:
And then your HTML should be fine as you have it:
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: