Using regular expressions to find img tags without an alt attribute

Viewed 18918

I am going through a large website (1600+ pages) to make it pass Priority 1 W3C WAI. As a result, things like image tags need to have alt attributes.

What would be the regular expression for finding img tags without alt attributes? If possible, with a wee explanation so I can use to find other issues.

I am in an office with Visual Web Developer 2008. The Edit >> Find dialogue can use regular expressions.

9 Answers

This is perfectly possible with following regEx:

<img([^a]|a[^l]|al[^t]|alt[^=])*?/?>

Looking for something that isn't there, is rather tricky, but we can trick them back, by looking for a group that doesn't start with 'a', or an 'a' that doesn't get followed by an 'l' and so on.

Simple and effective:

<img((?!\salt=).)*?

This regex works for find <img> tags missing the alt attribute.

I wrote a simple code for this without Regex

let arr = []
$('img')
.filter(function() {
  arr.push(this.alt)
})
document.write(arr.filter(a=>!a).length + ' img without alt tag')

<img(?!(\n|.(?!\/>))*?alt)

<img - Find start of image tag
(?! - begin negative lookahead
( - begin group
\n|.(?!\/>) - Match either a new line or anything not followed by end of the tag
)*? - close group. Match zero or more (non-greedy)
alt - Match "alt" literally
) end of negative lookahead

This one works for me in vscode. It will highlight the beginning of all the img tags without an alt attribute

Related