- Remove Special Characters From String in JavaScript
- Other Articles You’ll Also Like:
- About The Programming Expert
- Javascript string no special characters
- # Remove Special Characters from a String
- # Using the \w special character to shorten the regex
- # Excluding characters from being removed
- # Not keeping digits in the result
- # Specifying the characters we want to remove
- # Additional Resources
- How to Remove Special Characters From a String in JavaScript
- Shorten regular expression with \w character.
- 11 Amazing New JavaScript Features in ES13
Remove Special Characters From String in JavaScript
To remove special characters from a string in JavaScript, the easiest way to do this is to use the JavaScript String replace() method.
The regex in our code /[^a-z0-9]/gi will target any character that isn’t a letter or number.
Let’s see this code in action below.
var someString = "Th##is $is$ a% s_ho-rt** ^sent<>e[]nce^ with+= spe@@@cial |ch\aracters()()()!." someString = someString.replace(/[^a-z0-9]/gi, ""); console.log(someString); #Output: Thisisashortsentencewithspecialcharacters
If we want to allow spaces and periods as well, we would just have to add these to our regex code:
var someString = "Th##is $is$ a% s_ho-rt** ^sent<>e[]nce^ with+= spe@@@cial |ch\aracters()()()!." someString = someString.replace(/[^a-z0-9. ]/gi, ""); console.log(someString); #Output: This is a short sentence with special characters.
When using string variables in JavaScript, we can easily perform string manipulation to change the value of the string variables.
One such manipulation is to remove special characters from a string variable.
We can easily remove special characters from a string in JavaScript.
The easiest way to remove special characters from a string using JavaScript is with the JavaScript String replace() method.
The replace() method takes two arguments: the substring we want to replace, and the replacement substring. In this case, to remove special characters, we pass the regex expression we want (/[^a-z0-9 ]/gi) as the first argument, and an empty string (“”) as the second argument.
Let’s take a look at our code one last time for removing all special characters from a string.
Hopefully this article has been useful for you to learn how to remove special characters from a string in JavaScript.
Other Articles You’ll Also Like:
- 1. Using the appendChild Method with JavaScript to Add Items to a List
- 2. Using JavaScript to Run a Function Every 5 seconds
- 3. Using JavaScript to Round to 4 Decimal Places
- 4. Using JavaScript to Get the Current Year
- 5. Push Multiple Items to Array in JavaScript
- 6. Using JavaScript to get the Last Element in Array
- 7. Remove Undefined Values From an Array in JavaScript
- 8. Using JavaScript to Remove the First Character From a String
- 9. Reverse For Loop JavaScript
- 10. JavaScript tan – Find Tangent of Number in Radians Using Math.tan()
About The Programming Expert
The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.
Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.
At the end of the day, we want to be able to just push a button and let the code do it’s magic.
You can read more about us on our about page.
Javascript string no special characters
Last updated: Jul 25, 2022
Reading time · 3 min
# Remove Special Characters from a String
Use the replace() method to remove all special characters from a string, e.g. str.replace(/[^a-zA-Z0-9 ]/g, »); .
The replace() method will return a new string that doesn’t contain any special characters.
Copied!const str = 'hello 123 !@#$%^WORLD?.'; const noSpecialCharacters = str.replace(/[^a-zA-Z0-9 ]/g, ''); console.log(noSpecialCharacters); // 👉️ 'hello 123 WORLD'
The first argument we passed to the String.replace() method is a regular expression.
We used the g (global) flag to match all occurrences of the regex in the string and not just the first occurrence.
The square brackets [] part denotes a character class and the caret ^ symbol means «not the following characters».
After the ^ (not) symbol we specify:
- ranges of lowercase (a-z) and uppercase (A-Z) letters. This only applies to the Latin alphabet.
- a range of digits from (0-9).
- a space character.
In its entirety, the regular expression matches all characters but lowercase and uppercase letters, digits and spaces.
If you need to exclude other characters from being matched, add them between the square brackets [] of the regular expression.
If you don’t know the syntax for a specific character, check out the MDN regex syntax cheatsheet.
# Using the \w special character to shorten the regex
We could also shorten the regular expression by using the \w character.
Copied!const str = 'hello 123 !@#$%^WORLD?._'; const noSpecialCharacters = str.replace(/[^\w ]/g, ''); console.log(noSpecialCharacters); // 👉️ 'hello 123 WORLD_'
This is slightly different than our previous example because the \w character matches:
- ranges of lowercase (a-z) and uppercase (A-Z) letters. This only applies to the Latin alphabet.
- a range for digits from (0-9).
- underscores
A very convenient way to check what a specific character matches is to look at the MDN cheatsheet.
# Excluding characters from being removed
If you need to exclude other characters from being removed, add them between the square brackets of the regex.
Copied!const str = 'hello 123 !@#$%^WORLD?._'; const noSpecialCharacters = str.replace(/[^\w @]/g, ''); console.log(noSpecialCharacters); // 👉️ 'hello 123 @WORLD_'
I added the @ symbol between the square brackets of the regular expression to keep the character in the result.
Note that the caret ^ symbol has to be the first character in the square brackets for it to mean «not the following characters».
If you use the caret ^ symbol later on in the regex, it will get interpreted as a literal caret ^ symbol.
Note that the String.replace() method doesn’t change the original string. Instead, the method returns a new string with the matches replaced.
# Not keeping digits in the result
If you don’t want to keep the digits in the result, remove the digit range from the regular expression.
Copied!const str = 'hello 123 !@#$%^WORLD?.'; const noSpecialCharacters = str.replace(/[^a-zA-Z ]/g, ''); console.dir(noSpecialCharacters); // 👉️ 'hello WORLD'
If you end up removing an entire group of characters that is surrounded by spaces, the result might have multiple consecutive spaces.
You can use a regular expression if you need to replace multiple spaces with a single space.
Copied!const str = 'hello 123 !@#$%^WORLD?.'; const noSpecialCharacters = str.replace(/[^a-zA-Z ]/g, ''); console.dir(noSpecialCharacters); // 👉️ 'hello WORLD' const result = noSpecialCharacters.replace(/ +/g, ' '); console.dir(result); // 👉️ 'hello WORLD'
We used the plus + symbol to match one or more occurrences of a space and replaced multiple spaces with a single space.
# Specifying the characters we want to remove
An alternative approach to using the caret ^ symbol to specify the characters we want to keep is to specify the special characters we want to remove from the string.
Copied!const str = 'hello 123 !@#$%^WORLD?.<><>'; const noSpecialCharacters = str.replace( /[@!^&\/\\#,+()$~%.'":*?<><>]/g, '', ); console.log(noSpecialCharacters); // 👉️ "hello 123 WORLD"
We don’t have a caret ^ at the beginning of the character class, so the special characters in the square brackets get matched and removed from the string.
Some characters have a special meaning in regular expressions and have to be prefixed with a backslash to get treated as literal characters.
You can add all of the special characters you want to remove from the string between the square brackets.
If you ever need help reading a regular expression, check out this regex cheatsheet from MDN.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
How to Remove Special Characters From a String in JavaScript
To remove all special characters from a string, call the replace() method on the string, passing a whitelisting regex and an empty string as arguments, i.e., str.replace(/^a-zA-Z0-9 ]/g, ») . The replace() method will return a new string that doesn’t contain any special characters.
const str = 'milk and @#$%&!bread'; const noSpecialChars = str.replace(/[^a-zA-Z0-9 ]/g, ''); console.log(noSpecialChars); // milk and bread
The String replace() method searches a string for a value (substring or regular expression), and returns a new string with the value replaced by a substring. It doesn’t modify the original string.
The square brackets in the regular expression ( [] ) indicates a character class. Only characters that are enclosed in it will be matched.
But after placing the caret ( ^ ) as the first character in the square bracket, only characters that are not enclosed in the square bracket will be matched.
After the caret, we specify:
- ranges for lowercase ( a-z ) and uppercase ( A-Z ) letters.
- a range for digits from 0-9 .
- a space character ( ‘ ‘ ).
So the regex matches any character is not a lowercase or uppercase letter, digit or space, and the replace() method returns a new string with all of these characters removed from the original string.
The g (global) flag specifies that every occurrence of the pattern should be matched.
If we don’t pass a global flag, only the first special character in the string will be matched and removed.
const str = 'milk and @#$%&!bread'; // 👇 No 'g' flag in regex const noSpecialChars = str.replace(/[^a-zA-Z0-9 ]/, ''); // 👇 Only first special character removed console.log(noSpecialChars); // milk and #$%&!bread
Shorten regular expression with \w character.
We can shorten this regular expression a bit with the \w character.
const str = 'milk and @#$%&!bread'; const noSpecialChars = str.replace(/[^\w ]/g, ''); console.log(noSpecialChars); // milk and bread
The \w character matches uppercase and lowercase Latin letters, digits, and underscores.
Since \w matches underscores, it can’t be used on its own to remove this special character from a string.
const str = '_milk_ _and _@#$%&!_bread_'; const noSpecialChars = str.replace(/[^\w ]/g, ''); console.log(noSpecialChars); // _milk_ _and_ _bread_
We’ll need a different regex to remove the underscores:
const str = '_milk_ _and _@#$%&!_bread_'; const noSpecialChars = str.replace(/([^\w ]|_)/g, ''); console.log(noSpecialChars); // milk and bread
The pipe symbol ( | ) allows either of two patterns to be matched in a string, similar to a character class. To use the pipe symbol we need to wrap the two patterns in parentheses ( ( and ) ), which is what we did.
11 Amazing New JavaScript Features in ES13
This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.