代码之家  ›  专栏  ›  技术社区  ›  imvain2

用于从样式中删除高度/宽度的javascript regex

  •  1
  • imvain2  · 技术社区  · 6 年前

    使用ckeditor中的htmlfilter addrules,我试图从纯文本样式中删除高度/宽度。

    它们不会只返回纯文本样式的实际对象,因此我真的不能使用jquery或其他DOM操作工具。

    我有下面的regex代码,它成功地删除了高度和宽度,但仍然保留了实际的尺寸。

    我对正则表达式不太熟悉,所以我确信它相当简单。只是不确定。

    谢谢您。

    var str = "width:100px;height:200px;float:left;";
    var regex = /(height|width):(?=(.*?);)/gi;
    console.log(str.replace(regex,""));
    4 回复  |  直到 6 年前
        1
  •  1
  •   Wiktor Stribiżew    6 年前

    您使用了lookahead,它是一个非消耗模式,即它匹配的文本不会成为整个匹配值的一部分。因此,它不会被移除

    使用类似的模式

    /(?:height|width):[^;]*;/gi
    

    regex demo .

    细节

    见JS演示:

    var str = "width:100px;height:200px;float:left;";
    var regex = /(?:height|width):[^;]*;/gi;
    console.log(str.replace(regex,""));
        2
  •  1
  •   A l w a y s S u n n y    6 年前

    非正则表达式 解决方案,使用javascript内置方法删除 height/width 从纯文本样式。

    function isNotWidthHeight(style) {
      return style.toLowerCase().indexOf("width") === -1 && style.toLowerCase().indexOf("height") === -1 && style;
    }
    
    var str = "margin:0 auto;width:100px;height:200px;float:left;";
    var array = str.split(';').filter(isNotWidthHeight);
    console.log(array.join(';'));
        3
  •  0
  •   Code Maniac    6 年前

    您还需要捕获这些值。 .*? 而不是 (?=(.*?);) 就够了。

    var str = "width:100px;height:200px;float:left;";
    var regex = /(height|width):.*?;/gi;
    console.log(str.replace(regex,""));
        4
  •  0
  •   GenericUser    6 年前

    非常接近,你只需要一个额外的小组和一些事情等待 ; 或者单词边界, \b . 这将获取任何设置,包括 calc 或者任何设置,直到 ; 或内联样式的结尾。

    var str = "width:100px;height:200px;float:left;";
    var str2 = "width:calc(100vh - 20px);height:100%;float:left;";
    
    var regex = /((width|height):[\s\S]+?;|\b)/gi;
    console.log(str.replace(regex,""));
    console.log(str2.replace(regex,""));