【问题标题】:Commas not removed Javascript regex [duplicate]逗号未删除Javascript正则表达式[重复]
【发布时间】:2017-04-07 06:21:29
【问题描述】:

我正在尝试从字符串中删除所有非字母数字字符,然后继续计算从 pdf 中提取的每一行的字数。

var m = item["str"].replace(/[^a-zA-Z0-9 ]/g," ").trim().split(" ");
console.log("count: " + m.length + " words: " + m);

这是代码。结果输出示例:

计数:10 个字:The,Quick,Brown,Fox,,,Jumps,Over,The,Lazy

虽然 item["str"] 看起来像这样:

快速棕色狐狸 - 跳过懒惰

一些输出也看起来像这样:

计数:1 字:

谁能帮我理解这里发生了什么?提前致谢!

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    问题是您的正则表达式匹配单个字符并将其替换为空格。这会导致最终字符串中连续出现多个空格。

    让我们用你的例子:

    The Quick Brown Fox - Jumps Over The Lazy
    

    变成

    The Quick Brown Fox   Jumps Over The Lazy
    

    用空格分割会产生一些空字符串。


    您应该连续拆分多个空格以将其删除:split(/\s+/)

    function runReplace(str) {
      var m = str.replace(/[^a-zA-Z0-9 ]/g," ").trim().split(/\s+/);
      document.write(str + "<br/>");
      document.write("count: " + m.length + " words: " + m + "<br/>");
    }
    
    runReplace("The Quick Brown Fox - Jumps Over The Lazy");

    【讨论】:

    • /[^a-zA-Z0-9 ]+/g 不起作用,split("\s+") 语法无效。
    【解决方案2】:

    var item = {
        str: 'The Quick Brown Fox - Jumps Over The Lazy'
    };
    
    var output = item['str'].trim().replace(/\W/g, ' ').replace(/\s+/g, ' ').split(/\s/);
    
    console.log('length', output.length);
    console.log('output', output)

    我找到了 8 个单词而不是 10 个:v

    【讨论】:

    • 我会使用.replace(/\s+/g, ' ') 而不是.replace(/\s{2}/g, '')。您的代码不适用于双空格。
    • @Cerbrus 你是对的!
    【解决方案3】:

    你几乎完成了。只需做一件事,使用Array#filter 方法删除 Array 中的空参数

    var m = "The Quick Brown Fox - Jumps Over The Lazy".replace(/[^a-zA-Z0-9 ]/g," ").trim().split(" ").filter(a=> (a));
    console.log("count: " + m.length + " words: " + m.join(","));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-25
      • 1970-01-01
      • 1970-01-01
      • 2018-01-07
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多