Remove Special Characters From String Javascript

Jun 21, 2020

2 mins read

Published in

When working with strings in JavaScript, there might be scenarios where you need to remove special characters to sanitize or process the data. Let’s explore a simple solution to achieve this.

Approach 1 :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function removeSpecialCharacters(inputString) {
    // Use a regular expression to match and replace special characters
    return inputString.replace(/[^\w\s]/gi, '');
}

// Example usage:
const originalString = "Hello! This is a #sample string with $special characters.";
const sanitizedString = removeSpecialCharacters(originalString);

console.log("Original String:", originalString);
console.log("Sanitized String:", sanitizedString);

Explanation:

  1. The removeSpecialCharacters function takes an inputString as its parameter.
  2. Inside the function, replace method is used with a regular expression [^\w\s] to match any character that is not a word character (alphanumeric or underscore) or whitespace.
  3. The gi flags in the regular expression ensure a global and case-insensitive match.
  4. The matched special characters are then replaced with an empty string, effectively removing them from the original string.
  5. The sanitized string is returned.

Example Usage:

In the example provided, the original string contains special characters like ! and $. After applying the removeSpecialCharacters function, these special characters are removed, resulting in a sanitized string.

Approach 2 : Iterating Through Characters

Another approach is to iterate through each character in the string and build a new string without the special characters.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function removeSpecialCharactersIterative(inputString) {
  let result = '';
  for (let i = 0; i < inputString.length; i++) {
    const char = inputString[i];
    if (/[a-zA-Z0-9\s]/.test(char)) {
      result += char;
    }
  }
  return result;
}

Explanation:

  • The function iterates through each character in the input string.
  • The regex [a-zA-Z0-9\s] matches alphanumeric characters and whitespace.
  • Characters that match the pattern are added to the result string.
Performance Considerations:
  • The regex approach is concise and often performs well for large strings.
  • The iterative approach can be useful for specific cases or if you need more control over character processing.

In this blog post, we explored two effective approaches to remove special characters from a string in JavaScript. The choice between regex and iteration depends on the specific requirements of your application. Whether you prioritize readability, conciseness, or performance, these solutions provide a solid foundation for handling special characters in strings.

Sharing is caring!