修复链接内无ALT标签图片的ADA合规问题:正则表达式异常求助
Hey there! I see you're trying to add proper alt text to images inside links for ADA compliance, but your regex isn't working as expected—let's get that sorted out.
What Was Wrong with the Original Code?
Your original approach had two key issues:
- The regex pattern
/(\/+\.+\-+)w+?/doesn't target file names correctly—it's looking for a very specific, narrow pattern that won't match most standard image paths. - String methods like
replace()return a new string (they don't modify the original variable), so yourname.replace(...)line didn't actually update thenamevariable to use the extracted file name.
A Reliable Solution to Extract File Names
Instead of a fragile regex, let's use a more robust approach to pull the file name from the image's src attribute. This works for both relative paths (like /images/logo.png) and absolute URLs (like https://example.com/assets/photo.jpg?size=200).
Here's the updated code:
$("a > img").each(function () { const $image = $(this); // Check if alt is missing, empty, or only whitespace const currentAlt = $image.attr("alt"); if (!currentAlt || currentAlt.trim() === "") { let imageSrc = $image.attr("src"); // Step 1: Extract everything after the last slash (gets rid of path) let fileName = imageSrc.split("/").pop(); // Step 2: Remove any query parameters (like ?size=200) fileName = fileName.split("?")[0]; // Optional: Remove file extension for cleaner alt text (e.g., "logo" instead of "logo.png") // fileName = fileName.split(".").slice(0, -1).join("."); $image.attr("alt", fileName); } });
How This Works
split("/").pop(): Splits thesrcstring at every slash, then takes the last element (which is the file name with any query parameters).split("?")[0]: Removes any query string that might be appended to the image URL (common in CMS or CDN-hosted images).- Optional extension removal: If you want more human-readable alt text, uncomment the line that strips the file extension—this turns
header-banner.jpgintoheader-banner.
Alternative: Using a Regex for File Name Extraction
If you prefer using regex, here's a pattern that reliably captures the file name (ignoring paths and query parameters):
let fileName = imageSrc.match(/[^\/?#]+(?=[?#]|$)/)[0];
This regex matches the sequence of characters that comes after the last slash, and stops before any ?, #, or the end of the string.
Final Notes
- Make sure jQuery is loaded before your script (your existing
<script>tag for jQuery 3.3.1 is fine, just ensure it runs before your alt text script). - Test with different image paths to confirm it works for your site's setup—this method handles most common URL structures.
内容的提问来源于stack exchange,提问作者Dess

