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

如何用JS或jQuery移除粘贴的SVG代码中的width、height及id属性

实现方案

推荐使用DOM解析操作的方式实现,比正则匹配更稳定,不会出现误删内容的情况。

核心处理函数(原生JS实现,Vue可直接使用)

function cleanSvgCode(svgStr) {
  // 解析SVG字符串为DOM对象
  const parser = new DOMParser();
  const svgDoc = parser.parseFromString(svgStr, "image/svg+xml");
  const svgRoot = svgDoc.documentElement;

  // 移除svg根节点的width、height属性
  svgRoot.removeAttribute("width");
  svgRoot.removeAttribute("height");

  // 遍历所有子元素,移除所有id属性,不需要删data-name可删除对应行
  const allElements = svgRoot.querySelectorAll("*");
  allElements.forEach(el => {
    el.removeAttribute("id");
    el.removeAttribute("data-name");
  });

  // 转回字符串返回
  return new XMLSerializer().serializeToString(svgRoot);
}

Vue中使用示例

<template>
  <!-- 粘贴输入框 -->
  <textarea v-model="rawSvg" @input="handleSvgProcess" placeholder="请粘贴SVG代码"></textarea>
  <!-- 语法高亮展示区域 -->
  <div class="highlight-area" v-html="highlightedCode"></div>
</template>

<script>
export default {
  data() {
    return {
      rawSvg: '',
      highlightedCode: ''
    }
  },
  methods: {
    handleSvgProcess() {
      if (!this.rawSvg.trim()) {
        this.highlightedCode = ''
        return
      }
      // 先清理SVG代码
      const cleanedSvg = cleanSvgCode(this.rawSvg)
      // 传入语法高亮器处理后渲染
      this.highlightedCode = 你的语法高亮处理方法(cleanedSvg)
    }
  }
}
</script>

jQuery版本实现(如果需要)

function cleanSvgCodeJquery(svgStr) {
  const $temp = $("<div>").html(svgStr);
  const $svg = $temp.find("svg");
  // 移除根节点属性
  $svg.removeAttr("width height");
  // 移除所有子元素的id、data-name属性
  $svg.find("*").removeAttr("id data-name");
  return $temp.html();
}

该方案可以兼容各种属性写法(属性前后带空格、单双引号、换行写属性等场景),容错性远高于正则匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 06:06:00