Removing all spaces from a string using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a string and return a new space free string (a string in which all spaces are replaced by empty strings).

Example

Following is the code −

 Live Demo

const str = 'some random string ex a m pl e';
const removeSpaces = (str = '') => {
   let res = '';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(el !== ' '){
         res += el;
         continue;
      };
   };
   return res;
};
console.log(removeSpaces(str));

Output

somerandomstringexample
raja
Published on 19-Apr-2021 14:14:38
Advertisements