- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements