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

时间:2019-01-28 06:57:50

标签: javascript regex

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

  • 将多个空格替换为一个空格
  • 用单个逗号替换逗号前后的所有空格
  • 删除带空格的多个逗号
  • 删除逗号和结尾逗号

示例输入

  

“,这是A,,Test,,用于在js 123中找到正则表达式,”


预期输出:

  

“这是一个测试,可以在js 123中找到正则表达式”


到目前为止,我已经尝试过:

我想出了一种目前可以使用的解决方案。

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 个答案:

答案 0 :(得分:2)

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

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);

答案 1 :(得分:1)

我想出了一种目前可以使用的解决方案。

  

var str =“,这是A,,,Test,,用于在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