Using regular expressions to find img tags without an alt attribute

前端 未结 8 1865
伪装坚强ぢ
伪装坚强ぢ 2021-01-30 11:37

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

8条回答
  •  死守一世寂寞
    2021-01-30 12:01

    Building on Mr.Black and Roberts126 answers:

    /(]*)(>)/
    

    This will match an img tag anywhere in the code which either has no alt tag or an alt tag which is not followed by ="" or ='' (i.e. invalid alt tags).

    Breaking it down:

    (          : open capturing group
    (['"])]*      : match anything following the alt tag up to the closing '>' of the img tag
    )          : close capturing group
    (>)        : match the closing '>' of the img tag
    

    If your code editor allows search and replace by Regex you can use this in combination with the replace string:

    $1 alt=""$3
    

    To find any alt-less img tags and append them with an empty alt tag. This is useful when using spacers or other layout images for HTML emails and the like.

提交回复
热议问题