简体   繁体   English

如何使用正则表达式从内联样式中删除样式元素?

[英]How do I remove a style element from an inline style using regex?

I am trying to remove only one property ie float and its value, from an inline style.我试图从内联样式中仅删除一个属性,即float及其值。 I would like to start with this:我想从这个开始:

<div id="first_line_info" style="width:490px; float:right;"> </div>

And make it like this:并使它像这样:

<div id="first_line_info" style="width:490px"> </div>

So far I have tried this code:到目前为止,我已经尝试过这段代码:

Regex noInlineStylePattern = new Regex("style=\"[^\"]*\"", RegexOptions.IgnoreCase);
data = noInlineStylePattern.Replace(data, "");

This removes all of the inline styles.这将删除所有内联样式。 How can I just remove the float?我怎样才能去除浮动?

这应该删除所有浮点数:

data = Regex.Replace(data, @"(style=\"".*?)(float:\s*[^;\""]+;?)(.*?\"")", "$1$3", RegexOptions.IgnoreCase)

This code removes all attributes in style element except first attribute此代码删除样式元素中除第一个属性之外的所有属性

string test = @" <div id=""first_line_info"" style=""width:490px; float:right;""> </div>";

var result = Regex.Replace(test,"(style=\")(.*?;).*\"", new MatchEvaluator((m)=>
    {
        return m.Groups[1].Value + m.Groups[2].Value + @"""";
    }));

This code removes only float attribute from style element:此代码仅从样式元素中删除浮动属性

var result2 = Regex.Replace(test, "(style=\".*?;).*(float:.*?;)\"", new MatchEvaluator((m) =>
    {
        return m.Groups[1].Value + @"""";
    }));

We can achieve the same with DOM manipulation:我们可以通过 DOM 操作实现相同的效果:

var dom = document.createElement('div');
dom.innerHTML = `
  <div id="first_line_info" style="width:490px; float:right;"> </div>
  <div id="first_line_info1" style="width:490px;float:left;float:right"> </div>
`;
var elem = dom.getElementsByTagName('div');
var len = elem.length;

for (var i = 0; i < len; i++) {
  elem[i].style.float = null;
  //float removed
}

console.log(dom.innerHTML);

From dom-manipulation plus regex replace method:从 dom-manipulation 加上正则表达式替换方法:
advantage: just need to match float not style and float优点:只需要匹配浮动而不是样式和浮动

var dom = document.createElement('div');
dom.innerHTML = `
  <div id="first_line_info" style="width:490px; float:right;"> </div>
  <div id="first_line_info1" style="width:490px; float:right;float:left"> </div>
`;
var elem = dom.getElementsByTagName('div');
var len = elem.length;

for (var i = 0; i < len; i++) {
  var style = elem[i].getAttribute('style');
  var regex = /(float:\w+;*)/g;

  style = style.replace(regex, "");
  //float removed

  elem[i].setAttribute('style', style);
}

console.log(dom.innerHTML);

In the match group value, you could replace it.在匹配组值中,您可以替换它。

(float:.*?;)

1.  float:right;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM