Split Space Delimited String and Trim Extra Commas and Spaces in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say the following is our string −

var sentence = "My,,,,,,, Name,,,, is John ,,, Smith";

Use regular expression along with split() and join() to remove extra spaces and commas. Following is the code −


var sentence = "My,,,,,,, Name,,,, is John ,,, Smith";
console.log("Before removing extra comma and space="+sentence);
sentence = sentence.split(/[\s,]+/).join();
console.log("After removing extra comma and space=");

To run the above program, you need to use the following command −

node fileName.js.


Here, my file name is demo133.js. This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo133.js
Before removing extra comma and space=My,,,,,,, Name,,,, is John ,,, Smith
After removing extra comma and space=
Published on 11-Sep-2020 06:23:36