方法
const html = '<img src="image.jpg" style="width:100px;height:100px;">';
const newHtml = html.replace(/(<img[^>]*style=")(.*?)("[^>]*>)/g, (match, p1, p2, p3) => {
return p1 + 'new-style-value;' + p3;
});
console.log(newHtml); // 输出 <img src="image.jpg" style="new-style-value;">
介绍
- `<img`:匹配 `<img` 开头;
- `[^>]*`:匹配任意个非 `>` 字符;这是为了避免匹配到其他属性中包含 style 字符串的情况;
- `style="`:匹配 `style="`;
- `(.*?)`:捕获任意个非换行符的字符,且尽可能少地匹配;这是为了捕获 style 属性值;
- `"`:匹配 `"`;
- `[^>]*`:同上;
- `>`:匹配 `>` 结尾。