Split the sentences by comma and remove surrounding spaces - JavaScript?

Let’s say the following is our string with comma and whitespace −

var sentences = "  John ,    David ,         Bob ,      Mike,            Carol        ";

To split the sentences by comma, use split(). For removing surrounding spaces, use trim().


Following is the code −

var sentences = "  John , David , Bob , Mike, Carol ";
console.log("The value=" + sentences);
var result = sentences.split(",").map(function (value) {
   return value.trim();
console.log("After modifying the value=")

To run the above program, use the following command −

node fileName.js.

Here, my file name is demo235.js.


The output is as follows −

PS C:\Users\Amit\javascript-code> node demo235.js
The value=  John ,    David ,         Bob ,      Mike,            Carol        
After modifying the value=
[ 'John', 'David', 'Bob', 'Mike', 'Carol' ]

Updated on: 03-Oct-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started