Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Keeping only alphanumerals in a JavaScript string in JavaScript
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 that has all special characters replaced with their corresponding ASCII value, keeping only alphanumeric characters and spaces in their original form.
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
How It Works
The function checks each character using three conditions:
-
+str[i]- Checks if the character is a numeric digit -
str[i].toLowerCase() !== str[i].toUpperCase()- Checks if the character is a letter -
str[i] === ' '- Checks if the character is a space
If any condition is true, the character is kept as-is. Otherwise, it's replaced with its ASCII value using charCodeAt(0).
Alternative Approach Using Regex
Here's a more concise solution using regular expressions:
const str = 'Th!s !s @ str!ng th@t cont@!ns some special characters!!';
const specialToASCIIRegex = str => {
return str.replace(/[^a-zA-Z0-9 ]/g, match => match.charCodeAt(0));
};
console.log(specialToASCIIRegex(str));
Th33s 33s 64 str33ng th64t cont6433ns some special characters3333
Conclusion
Both approaches effectively replace special characters with ASCII values while preserving alphanumeric characters and spaces. The regex method is more concise, while the loop method offers more explicit control over the logic.
