Computer >> Computer tutorials >  >> Programming >> Javascript

Removing all spaces from a string using JavaScript


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 −

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