Nadim Hossain Sonet
Nadim Hossain Sonet

Reputation: 1709

Filter Comma and Whitespace in String using Regular Expression in JavaScript

I want to filter a string using regular expression so that:


Sample Input:

" , This, is A ,,, Test , , to find regex,,in js 123 , "


Expected Output:

"this,is a,test,to find regex,in js 123"


What I have tried so far:

I have came up with a solution that is working so far.

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

Upvotes: 1

Views: 968

Answers (1)

JasonR
JasonR

Reputation: 401

First, remove all spaces next to commas:

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

Second, replace all consecutive commas with single commas and all consecutive spaces with single spaces:

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

Finally, remove leading and trailing commas:

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

Upvotes: 2

Related Questions