Write a Regular Expression to remove all special characters from a JavaScript String?

To remove all special characters from a JavaScript string, you can use regular expressions with the replace() method. The most common approach is using the pattern /[^\w\s]/g which matches any character that is not a word character or whitespace.

Syntax

string.replace(/[^\w\s]/g, '')

Regular Expression Breakdown

The pattern /[^\w\s]/g works as follows:

  • [^...] - Negated character class (matches anything NOT in the brackets)
  • \w - Word characters (a-z, A-Z, 0-9, _)
  • \s - Whitespace characters (spaces, tabs, newlines)
  • g - Global flag (replace all occurrences)

Example: Basic Special Character Removal

<html>
<head>
<script>
var str = "@!Welcome to our website$$";
document.write("Original: " + str);

// Removing Special Characters
var cleaned = str.replace(/[^\w\s]/g, '');
document.write("<br>Cleaned: " + cleaned);
</script>
</head>
<body>
</body>
</html>
Original: @!Welcome to our website$$
Cleaned: Welcome to our website

Different Approaches

Method 1: Keep Letters, Numbers, and Spaces

<html>
<head>
<script>
var text = "Hello@World! #2023$ Test%";
var result = text.replace(/[^\w\s]/g, '');
document.write("Result: " + result);
</script>
</head>
<body>
</body>
</html>
Result: HelloWorld 2023 Test

Method 2: Keep Only Letters and Spaces

<html>
<head>
<script>
var text = "Hello123@World! #Test%";
var result = text.replace(/[^a-zA-Z\s]/g, '');
document.write("Letters only: " + result);
</script>
</head>
<body>
</body>
</html>
Letters only: HelloWorld Test

Method 3: Remove Spaces Too

<html>
<head>
<script>
var text = "Hello @World! Test";
var result = text.replace(/[^\w]/g, '');
document.write("No spaces: " + result);
</script>
</head>
<body>
</body>
</html>
No spaces: HelloWorldTest

Comparison Table

Pattern Keeps Example Input Output
/[^\w\s]/g Letters, numbers, underscores, spaces "Hello@123 World!" "Hello123 World"
/[^a-zA-Z\s]/g Only letters and spaces "Hello@123 World!" "Hello World"
/[^\w]/g Letters, numbers, underscores "Hello@123 World!" "Hello123World"

Common Use Cases

  • Cleaning user input for database storage
  • Creating URL-friendly strings
  • Sanitizing form data
  • Preparing text for search functionality

Conclusion

Use /[^\w\s]/g as the standard pattern to remove special characters while preserving letters, numbers, and spaces. Adjust the pattern based on your specific requirements for what characters to keep.

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

768 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements