代码之家  ›  专栏  ›  技术社区  ›  Nadim Hossain Sonet

在JavaScript中使用正则表达式过滤字符串中的逗号和空白

  •  0
  • Nadim Hossain Sonet  · 技术社区  · 7 年前

    我想使用正则表达式筛选字符串,以便:

    • 多个空间替换为单个空间
    • 删除带空格的多个逗号
    • 删除开始和结束逗号

    样本输入:

    ,这是一个,,,测试,用于在js 123中查找regex


    预期产量:


    到目前为止我所做的:

    到目前为止,我已经想出了一个可行的解决方案。

    var str = " , This, is A ,,, Test , , to find regex,,in js 123 , ";
    
    str = str.replace(/ +/g, " "); //replace multiple space with single space
    str = str.replace(/\s*,\s*/g, ","); //replace space before and after comma with single comma
    str = str.replace(/,+/g, ","); //remove multiple comma with single comma
    str = str.replace(/^,|,$/g, ""); //remove starting and ending comma
    
    console.log(str);
    2 回复  |  直到 7 年前
        1
  •  2
  •   Stephan T.    7 年前

    首先,删除逗号旁边的所有空格:

    replace(/ *, */g, ’,’)
    

    其次,将所有连续逗号替换为单个逗号,将所有连续空格替换为单个空格:

    replace(/,+/g, ‘,’)
    replace(/ +/g, ‘ ‘)
    

    replace(/^,/, ‘’)
    replace(/,$/, ‘’)
    

    var str = " , This, is A ,,, Test , , to find regex,,in js 123 , ";
    str = str.replace(/^[\s,]+|[\s,]+$|\s*(\s|,)[\s,]*/g, "$1");
    console.log(str);
        2
  •  1
  •   Nadim Hossain Sonet    7 年前

    var str=“,This,是一个,,,Test,用于在js 123中查找regex,”;


    str = str.replace(/ +/g, " "); //replace multiple space with single space
    str = str.replace(/\s*,\s*/g, ","); //replace space before and after comma with single comma
    str = str.replace(/,+/g, ","); //remove multiple comma with single comma
    str = str.replace(/^,|,$/g, ""); //remove starting and ending comma