你不需要一个dom来解析html标记!!!
这是最快的方法,而且不会被格式错误的html阻塞。
查找
/<img(?=\s)(?=(?:[^>"']|"[^"]*"|'[^']*')*?\ssrc\s*=\s*(?:(['"])(?:(?!\1)[\S\s])*?((?:(?!\1|\\)[\S\s])*?)\.png\s*\1))\s+(?:"[\S\s]*?"|'[\S\s]*?'|[^>]?)+>/
替换
*$2*
https://regex101.com/r/bCYXV1/1
解释
# Begin 'img' tag
< img
(?= \s )
(?= # Asserttion (a pseudo atomic group)
(?: [^>"'] | " [^"]* " | ' [^']* ' )*?
\s src \s* = \s* # src attribute
(?:
( ['"] ) # (1), Quote
(?:
(?! \1 )
[\S\s]
)*?
( # (2 start)
(?:
(?! \1 | \\ )
[\S\s]
)*?
) # (2 end)
\.png # find the 'png' file
\s*
\1
)
)
# Have the png file, just match the rest of tag
\s+
(?: " [\S\s]*? " | ' [\S\s]*? ' | [^>]? )+
> # End img tag
var input = "dsd<img src=\"assets\\test\\1F619.png\"><img src=\"assets\\test\\1F619.png\"><img src=\"assets\\test\\1F629.png\"><img src=\"assets\\test\\1F630.png\">sdfsdfsdffsdf<img src=\"assets\\test\\1F629.png\">sdfsdsdfsdf<img src=\"assets\\test\\1F627.png\"><img src=\"assets\\test\\1F631.png\">sdfsdfsdf<img src=\"assets\\test\\1F631.png\">sdfsdfsdf<img src=\"assets\\test\\1F632.png\">sdfsdfs<img src=\"assets\\test\\1F629.png\"><img src=\"assets\\test\\1F629.png\">sdfs<img src=\"assets\\test\\1F631.png\">df<img src=\"assets\\test\\1F632.png\">sdfsdfsdf";
console.log(input.replace(/<img(?=\s)(?=(?:[^>"']|"[^"]*"|'[^']*')*?\ssrc\s*=\s*(?:(['"])(?:(?!\1)[\S\s])*?((?:(?!\1|\\)[\S\s])*?)\.png\s*\1))\s+(?:"[\S\s]*?"|'[\S\s]*?'|[^>]?)+>/g
,"\n*$2*"));