Trim and split string to form array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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' ]
raja
Published on 23-Nov-2020 10:24:05
Advertisements