Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to remove multiple comma and spaces from string in javascript [closed]

Tags:

I have a string like

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

in which there are multiple spaces in beginning,middle and end of string with commas. i need this string in

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

i found many regex in forum removing spaces , commas separately but i could not join them to remove both.

Please give explanation of regex syntex to if possible .

Thanks in advance

like image 323
Dashrath Avatar asked Oct 08 '13 10:10

Dashrath


People also ask

How to get rid of commas regex?

To remove all commas from a string, call the replace() method, passing it a regular expression to match all commas as the first parameter and an empty string as the second parameter. The replace method will return a new string with all of the commas removed.

How to remove comma from a number in JavaScript?

var a='1,125'; a=a. replace(/\,/g,''); // 1125, but a string, so convert it to number a=parseInt(a,10);

How do you change a comma with spaces in a string?

Use the replace() method to replace all commas in a string, e.g. str. replace(/,/g, ' ') . The method takes a regular expression and a replacement string as parameters and returns a new string with the matches replaced by the provided replacement. Copied!


2 Answers

You can just replace every space and comma with space then trim those trailing spaces:

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

jsfiddle demo

like image 137
Jerry Avatar answered Oct 15 '22 02:10

Jerry


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

RegEx Explained and Demo

like image 29
Vinay Pratap Singh Bhadauria Avatar answered Oct 15 '22 01:10

Vinay Pratap Singh Bhadauria