You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中如何修改字符串变量内各<img>标签的尺寸

调整HTML字符串中img标签的宽高尺寸

实现思路

通过正则匹配<img>标签样式里的height和width数值,将数值除以2后替换原内容,得到修改后的HTML字符串。

代码实现

const html = `<p><img alt="" src="https://media.cheggcdn.com/media%2F1cb%2F1cb8a6aa-8dbf-4cc1-90ae-e214d46eb4c1%2Fphp7FkMW8.png"style="height:34px;width:158px;" /></p><p><strong>explanation:</strong></p><p><strong><img alt="" src="https://media.cheggcdn.com/media%2F7f8%2F7f87506b-9fb5-421f-85e6-b283732266d2%2FphprAsgze.png"style="height:130px;width:387px;" /></strong></p>`;

// 全局匹配height/width的数值,完成替换
const modifiedHtml = html.replace(/(height|width):(\d+)px/g, (match, prop, value) => {
  const newValue = parseInt(value) / 2;
  return `${prop}:${newValue}px`;
});

console.log(modifiedHtml);

代码说明

  • 正则/(height|width):(\d+)px/g:全局匹配样式中height:或width:后跟数字加px的格式,同时捕获属性名和数值部分。
  • 替换函数里把捕获到的数值转成整数后除以2,再拼接成新的样式片段返回,自动处理奇数数值(比如387px会转为193.5px)。

内容的提问来源于stack exchange,提问作者vpn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 08:54:20