Replace all special character from string in JavaScript

In many places in programming, we want to replace special character with _ or anything else. There are many ways to replace but I am going to use replace function with regular expression.

Syntax:

replace(pattern, replacement)
OR
replaceAll(pattern, replacement)

To capture all special character including space we can use \W regular expression. (It does not include underscore (_))

\W -> matches any non-word character (equivalent to [^a-zA-Z0-9_])

Example:

let str = 'I am # number of | but not I have %&! etc'
str.replace(/\W/g, "A") // 'IAamAAAnumberAofAAAbutAnotAIAhaveAAAAAetc'
str.replaceAll(/\W/g, "A") // 'IAamAAAnumberAofAAAbutAnotAIAhaveAAAAAetc'

Leave a Reply