Sometime you may need to remove special characters from a string containing special characters. This may even be useful when decrypting some data. Or sometimes, just for validating a user input. Here in these examples, I’ll show you how you can use the replace() method provided by JavaScript with a regex pattern to remove such characters.
const someString = '$s(o/m,e_@h*i-}dde##n_m.?es!(s)ag[e]'
const anotherString = '.o;;;;n#e_m(o)r?e_{s}}ecr+=et_me@!ss%^a*g$$e'
function removeSpecialCharacters(charactersString) {
return charactersString.replace(/[^\w\s]/gi, '')
}
console.log(removeSpecialCharacters(someString))
console.log(removeSpecialCharacters(anotherString))
//output
some_hidden_message
one_more_secret_message
Code language: JavaScript (javascript)
You can even remove the single or double quotes from a string using the regex above. However, you need to keep in mind that you’ll have to use string interpolation in such cases to avoid string’s end-of-line mismatching. That is, instead of writing “Peter’s mother’s name ends with “a””, you could write `Peter’s mother’s name ends with “a” ` without having to switch between single and double quotes. Here’s an example to demonstrate the same:
const stringWithQuotes = `'y"e~t_$a%no(t**her_s//ec]re''t_m;e$ss^a*ge`
console.log(removeSpecialCharacters(stringWithQuotes))
//output
yet_another_secret_message
Code language: JavaScript (javascript)
If you have any doubts or suggestions, let me know in the comments below!