如何使用RegExp和.replace()函数从th标签中删除width属性

时间:2018-05-03 06:26:18

标签: jquery

我有一张桌子

<thead id="tag_1985_103">
 <tr id="tag_1983_103">
  <th width="33.33%"  id="tag_1981_103" rowspan="1" colspan="1">Col 1 </th>
  <th width="33.63%"  id="tag_1980_103" rowspan="1" colspan="1">Col 2 </th>
  <th width="33.65%"  id="tag_1979_103" rowspan="1" colspan="1">Col 3 </th>
 </tr>
</thead>

我需要从每个标签中删除width属性,该值不是唯一的。 我尝试了以下代码,但没有工作..

var strcontent ='<thead id="tag_1985_103">
<tr id="tag_1983_103">
<th width="33.33%"  id="tag_1981_103" rowspan="1" colspan="1">Col 1 
</th>
<th width="33.63%"  id="tag_1980_103" rowspan="1" colspan="1">Col 2 </th>
<th width="33.65%"  id="tag_1979_103" rowspan="1" colspan="1">Col 3 </th>
</tr>
</thead>';
var srch_pattern = new RegExp('<th width="(\d+)" ([^>]+)>', "gi");
var replace_pattern = '<th $1>';
strcontent = strcontent.replace(srch_pattern, replace_pattern);

请建议我一个解决方案

2 个答案:

答案 0 :(得分:2)

如果您只想删除width="value",可以使用strcontent = $(strcontent).find("th").removeAttr("width").closest("thead")[0].outerHTML;

我们将其转换为对象,然后移除宽度。

<强>演示

$("table thead tr th").removeAttr('width');


var strcontent ='<thead id="tag_1985_103"><tr id="tag_1983_103"><th width="33.33"  id="tag_1981_103" rowspan="1" colspan="1">Col 1 </th><th width="33.63"  id="tag_1980_103" rowspan="1" colspan="1">Col 2 </th><th width="33.65"  id="tag_1979_103" rowspan="1" colspan="1">Col 3 </th></tr></thead>';

strcontent = $(strcontent).find("th").removeAttr("width").closest("thead")[0].outerHTML;

console.log(strcontent)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead id="tag_1985_103">
    <tr id="tag_1983_103">
      <th width="33.33" id="tag_1981_103" rowspan="1" colspan="1">Col 1
      </th>
      <th width="33.63" id="tag_1980_103" rowspan="1" colspan="1">Col 2 </th>
      <th width="33.65" id="tag_1979_103" rowspan="1" colspan="1">Col 3 </th>
    </tr>
  </thead>
</table>

答案 1 :(得分:0)

试试这个

$(function(){
    var html = '<thead id="tag_1985_103">\r\n'+
       '<tr id="tag_1983_103">\r\n'+
            '<th width="33.33" id="tag_1981_103" rowspan="1" colspan="1">Col 1 </th>\r\n'+
            '<th width="33.63" id="tag_1980_103" rowspan="1" colspan="1">Col 2 </th>\r\n'+
            '<th width="33.65" id="tag_1979_103" rowspan="1" colspan="1">Col 3 </th>\r\n'+
        '</tr>\r\n'+
    '</thead>\r\n';     
    console.log(html);
    
    var converted = html.replace(/<th\s\width*=.+?=/gi, '<th id=')
    console.log(converted);
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>