Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space javascript javascript

Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space


Be aware, that \W leaves the underscore. A short equivalent for [^a-zA-Z0-9] would be [\W_]

text.replace(/[\W_]+/g," ");

\W is the negation of shorthand \w for [A-Za-z0-9_] word characters (including the underscore)

Example at regex101.com


Jonny 5 beat me to it. I was going to suggest using the \W+ without the \s as in text.replace(/\W+/g, " "). This covers white space as well.


Since [^a-z0-9] character class contains all that is not alnum, it contains white characters too!

 text.replace(/[^a-z0-9]+/gi, " ");