方法
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 属性值;
- `"`:匹配 `"`;
- `[^>]*`:同上;
- `>`:匹配 `>` 结尾。
该文章展示了如何用JavaScript的正则表达式方法查找并替换HTMLimg标签中的style属性值,以实现对图片样式的动态修改。通过匹配<img>标签并捕获style属性,然后插入新的样式值,可以更新img元素的样式。

910

被折叠的 条评论
为什么被折叠?



