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

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



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 −

Example

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=");
console.log(sentence)

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

node fileName.js.

Output

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=
My,Name,is,John,Smith
Updated on: 2020-09-11T06:25:40+05:30

386 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements