
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Trim and Split String to Form Array in JavaScript
Suppose, we have a comma-separated string like this −
const str = "a, b, c, d , e";
We are required to write a JavaScript function that takes in one such and sheds it off all the whitespaces it contains.
Then our function should split the string to form an array of literals and return that array.
Example
The code for this will be −
const str = "a, b, c, d , e"; const shedAndSplit = (str = '') => { const removeSpaces = () => { let res = ''; for(let i = 0; i < str.length; i++){ const el = str[i]; if(el === ' '){ continue; }; res += el; }; return res; }; const res = removeSpaces(); return res.split(','); }; console.log(shedAndSplit(str));
Output
And the output in the console will be −
[ 'a', 'b', 'c', 'd', 'e' ]
Advertisements