Was it helpful?

Question

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

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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().

Example

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

To run the above program, use the following command −

node fileName.js.

Here, my file name is demo235.js.

Output

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' ]
raja
Published on 03-Oct-2020 18:39:39
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top