js 正则只替换img标签中style

2026-01-12 08:32:24
//  js 正则只替换img标签中style
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 属性值;
//    `"`:匹配 `"`;
//   `[^>]*`:同上;
//   `>`:匹配 `>` 结尾。

这样就可以替换任意其他标签了!!

例如:

const html1 = '<img title="test title" src="xxxyyzys.jpg">';
const newHtml = html1.replace(/(<img[^>]*src=")(.*?)("[^>]*>)/g, (match, p1, p2, p3) => {
  return p1 + 'new-src-value.jpg' + p3;
});

console.log(newHtml); // 输出 <img title="test title" src="new-style-value.jpg">
免责申明:本站内容大部分来自互联网,部分来源于个人原创。仅供个人学习使用,本站不承担任何法律责任。如有侵权请联系删除!