Regex to remove multiple commas and spaces from a string in javascript

I have a line like

var str=" , this, is a ,,, test string , , to find regex,,in js. , "; 

in which there are several spaces at the beginning, middle and end of the line with commas. I need this line in

 var str="this is a test string to find regex in js."; 

I found a lot of regex in the forums to remove spaces, commas separately, but I could not join them to remove both.

Please explain, if possible, regex syntex.

Thanks in advance

+7
javascript regex
source share
4 answers

You can simply replace each space and comma with a space, then trim these trailing spaces:

 var str=" , this, is a ,,, test string , , to find regex,,in js. , "; res = str.replace(/[, ]+/g, " ").trim(); 

jsfiddle demo

+17
source share

Try something like this:

 var new_string = old_string.replace(/[\s,]+/g,' ').trim(); 

The regular expression is just [\s,]+ , if we need to split it into \s , it means ANY whitespace character, and , - a literal comma. [] is a set of characters (an array of thoughts), and + means one or more matches.

If you just need space, not spaces, you can replace \s with literal space.

We insert /g at the end so that it does a global search and replace, otherwise it would just do it for just one match.

+1
source share

you can use reg ex for this

 /[,\s]+|[,\s]+/g var str= "your string here"; //this will be new string after replace str = str.replace(/[,\s]+|[,\s]+/g, 'your string here'); 

Explained and Demonstrated RegEx

+1
source share

You should be able to use

  str.replace (/, / g, "");

"g" is the key, you may need to use [,]

0
source share

All Articles