【问题标题】:Replacing consecutive whitespace with one whitespace character用一个空格字符替换连续的空格
【发布时间】:2011-10-04 16:54:46
【问题描述】:

我想使用 JavaScript 用一个空白字符替换两次或多次出现的空白(此代码将位于 chrome 扩展中)。

【问题讨论】:

    标签: javascript regex string


    【解决方案1】:
    "    this is    tooo    spaced      ".replace(/\s+/g, " ");
    

    返回

    " this is tooo spaced "
    

    【讨论】:

    • 这匹配一个。 OP 正在寻找“不止一个”。 /\s{2,}/g 会更有意义(尽管你的仍然有效)。
    【解决方案2】:

    你可以同时做到这两点:

    "str   str\t\t\tstr".replace(/(\s)+/g, "$1");
    

    【讨论】:

    • 不知道 \s 也匹配 \t。令人印象深刻!
    • @Davide 我现在将如何用空格替换制表符?我应该做另一个循环吗?
    • 如果你想用空格替换所有的空白字符,你应该简单地使用 davin 写的。我添加了我的示例,因为我认为您希望将多个选项卡替换为选项卡,将多个空格替换为空格等。
    【解决方案3】:

    对于空格:

    'test   with   spaces'.replace( /\s+/g, ' ' );
    

    对于标签:

    'test\t\t\twith\t\t\ttabs'.replace( /\t+/g, '\t' );
    

    【讨论】:

      猜你喜欢
      • 2011-04-21
      • 2013-03-31
      • 2020-03-16
      • 2015-03-27
      • 2011-05-13
      • 1970-01-01
      • 2012-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多