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
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.
var a='1,125'; a=a. replace(/\,/g,''); // 1125, but a string, so convert it to number a=parseInt(a,10);
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!
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With