Answered
How can I easily remove all the special characters from my JavaScript strings?
Things like question marks, periods, hashes, parenthesis, etc. need to be removed.
For instance, I'll commonly have any of these characters in a string:
"my string 123@!#%^$?";
That string would need to be converted into this:
"my string123"
Thanks for the help in advance!
Try this regular expression and replace()
method:
myString = myString.replace(/[^\w ]/g, "");
This will remove the special characters from your string.
Another regular expression you can use:
let string = "my string 123@!#%^$?";
string = string.replace(/[^a-zA-Z0-9 ]/g, "");
// string = "my string 123"
The regular expression all characters besides letters and numbers.
const newString = ogString.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, "");
This regular expression allows you to specifically list which special characters you want removed. Notice that some characters are escaped using \
.
This should work for removing the special characters from your strings.
If you want to remove all special characters from your string, use this regex:
string.replace(/[^a-z0-9,. ]/gi, "");
The pattern is [^a-z0-9,. ]
. Which means it will match any characters besides spaces, letters, numbers, periods, or commas.
You can also use a regex that removes only specific characters:
string.replace(/[@!#%^$?]/g, "");
This will match and replace the following characters: @
, !
, #
, %
, ^
, $
, ?
.
function removeSpecialCharacters(string) {
return string
.replace(/(?!\w|\s)./g, "")
.replace(/\s+/g, " ")
.trim();
}
A quick breakdown of each part:
.replace(/(?!\w|\s)./g, "")
: replaces everything in the string besides alphanumeric characters and spaces..replace(/\s+/g, " ")
: finds any instance of two consecutive spaces and replaces it with one space..trim()
: removes any white space at the beginning or end of the string.To use the function, you can just pass in your string as the parameter:
removeSpecialCharacters(ogString)