
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Keep Only Alphanumerals in a JavaScript String
We are required to write a JavaScript function that takes in a string that might contain some special characters.
The function should return a new string should have all special characters replaced with their corresponding ASCII value.
Therefore, let’s write the code for this function −
Example
The code for this will be −
const str = 'Th!s !s @ str!ng th@t cont@!ns some special characters!!'; const specialToASCII = str => { let res = ''; for(let i = 0; i < str.length; i++){ if(+str[i] || str[i].toLowerCase() !== str[i].toUpperCase() || str[i] === ' '){ res += str[i]; continue; }; res += str[i].charCodeAt(0); }; return res; }; console.log(specialToASCII(str));
Output
The output in the console will be −
Th33s 33s 64 str33ng th64t cont6433ns some special characters3333
Advertisements