How to add a class to a hyperlink when it contains a specific file extension?
Can someone tell me how to take a string and run a function against it to check for a specific type of file (say 开发者_如何学Goa ".pdf"). If the string contains the file, then it needs to apply a "pdf" class to the anchor that contains the link.
Here's an example of a string:
<a href="/downloads/myfile.pdf">My PDF</a>
I would like it to be changed to this:
<a href="/downloads/myfile.pdf" class="pdf">My PDF</a>
Do this in CSS:
a[href$=".pdf"] {
/* some rules */
}
But this may not be supported by some browser.
Alternatively, do this in Javascript, with jQuery or any library:
$('a[href$=".pdf"]').addClass('pdf'); // in jQuery
Or without library:
var elems = document.getElementByTagName('a');
for (var i = 0; i < elems.length; ++i) {
var a = elems[i];
if (/\.pdf$/.test(a.href)) {
a.className = 'pdf';
}
}
(<a\s+href="[^"]*\.([A-Za-z0-9]{2,5})\s*")([^>]*>)
replace by
\1 class="\2" \3
python code:
import re,sys
file = sys.argv[1]
f = open(file, 'r')
text = f.read()
f.close()
text = re.sub(r'(<a\s+href="[^"]*\.([A-Za-z0-9]{2,5})\s*")([^>]*>)', r'\1 class="\2" \3', te$
f = open(file+'.re','w')
f.write(text)
f.close()
Can use it to modify html static
精彩评论