- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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().
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' ]
Advertisements