【问题标题】:Remove spaces at the end of class attribute删除类属性末尾的空格
【发布时间】:2015-12-05 14:05:21
【问题描述】:

我想删除此字符串中class 属性末尾的空格:

<div class="test  wrapper   " id="test"> " sample text " </div>

如果我使用

text = text.replace(/\s+"/g, '"');

那么sample text 后面的空格也将被删除,我想保留那个空格。

你知道我该怎么做吗?

【问题讨论】:

  • 一般来说,你应该用正则表达式来做。在这种特定情况下,您可以替换 replace(/\s+"&gt;/g, '"&gt;');
  • @ndn 类可能不是最后一个属性,那么您知道我该怎么做吗?
  • replace(/\s+"([^&gt;]*)&gt;/g, '"$1&gt;');,但还是要使用 html 解析器。

标签: javascript regex html-parsing


【解决方案1】:

让你的正则表达式更具体

通过在您的正则表达式中添加class=",您可以缩小替换范围。然后使用捕获组()$n 替换模式,您可以只保存不包括任何空格的类名列表:

var text = '<div class="test  wrapper   " id="test"> " sample test " </div>';
text = text.replace(/class="\s*(.+?)\s*"/g, 'class="$1"');
alert(text);

【讨论】:

    【解决方案2】:

    如果你想要的结果看起来像
    “样品测试”
    然后使用此代码 使用 js

    var str = "样本测试";
    var newStr = str.trim();
    // “样本测试”

    js 和正则表达式
    使用此代码:

    var str = "样本测试";
    var newStr = str.replace(/(^\s+|\s+$)/g,'');
    // "样本测试"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多