Replacing all special characters with their ASCII value in a string - 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 with all special characters replaced with their corresponding ASCII value.

Understanding Special Characters

Special characters are symbols that are not letters, numbers, or spaces. Examples include !, @, #, $, etc. Each character has a unique ASCII code that can be retrieved using the charCodeAt() method.

Example

Following is the code:

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++){
        // Check if character is alphanumeric or space
        if(+str[i] || str[i].toLowerCase() !== str[i].toUpperCase() || str[i] === ' '){
            res += str[i];
            continue;
        };
        // Replace special character with ASCII code
        res += str[i].charCodeAt(0);
    };
    return res;
};

console.log(specialToASCII(str));

Output

Th33s 33s 64 str33ng th64t cont6433ns some special characters3333

How It Works

The function iterates through each character and uses three conditions to identify alphanumeric characters and spaces:

  • +str[i] - Converts to number, returns truthy for digits
  • str[i].toLowerCase() !== str[i].toUpperCase() - Returns true for letters
  • str[i] === ' ' - Checks for space character

If none of these conditions are met, the character is considered special and replaced with its ASCII value using charCodeAt(0).

Alternative Approach Using Regular Expressions

const str = 'Hello@ World! #2023';

const replaceSpecialWithASCII = str => {
    return str.replace(/[^a-zA-Z0-9\s]/g, (char) => char.charCodeAt(0));
};

console.log(replaceSpecialWithASCII(str));
Hello64 World33 352023

Comparison

Method Performance Readability Browser Support
For Loop Faster Moderate All browsers
Regular Expression Slower Higher All modern browsers

Conclusion

Both methods effectively replace special characters with ASCII values. The for loop approach offers better performance, while the regex method provides cleaner, more readable code for simple transformations.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements