Removing all non-alphabetic characters from a string in JavaScript


We are required to write a JavaScript function that takes in a string of characters. The function should construct a new string in which all the non-alphabetic characters from the original string are removed and return that string. If the string contains spaces, then it should not be removed.

For example −

If the input string is −

const str = 'he@656llo wor?ld';

Then the output string should be −

const str = 'he@656llo wor?ld';

Example

Following is the code −

const str = 'he@656llo wor?ld';
const isAlphaOrSpace = char => ((char.toLowerCase() !==
char.toUpperCase()) || char === ' ');
const removeSpecials = (str = '') => {
   let res = '';
   const { length: len } = str;
   for(let i = 0; i < len; i++){
      const el = str[i];
      if(isAlphaOrSpace(el)){
         res += el;
      };
   };
   return res;
};
console.log(removeSpecials(str));

Output

Following is the output on console −

hello world

Updated on: 11-Dec-2020

331 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements