Problem
We are required to write a JavaScript function that takes in a string and removes all special characters from the string leaving behind just alphabets and numerals in the resultant string.
Input
const str = 'th@is Str!ing Contains 3% punctuations';
Output
const output = 'thisStringContains3punctuations';
Because we removed all punctuations and whitespaces
Example
Following is the code −
const str = 'th@is Str!ing Contains 3% punctuations';
const removeSpecialChars = (str = '') => {
let res = '';
for(let i = 0; i < str.length; i++){
const el = str[i];
if(+el){
res += el;
}else if(el.toLowerCase() !== el.toUpperCase()){
res += el;
};
continue;
};
return res;
};
console.log(removeSpecialChars(str));Output
thisStringContains3punctuations