Sometimes, we want to replace all non alphanumeric characters, new lines, and multiple white space with one space with JavaScript.
In this article, we’ll look at how to replace all non alphanumeric characters, new lines, and multiple white space with one space with JavaScript.
How to replace all non alphanumeric characters, new lines, and multiple white space with one space with JavaScript?
To replace all non alphanumeric characters, new lines, and multiple white space with one space with JavaScript, we can use the string replace
method with a regex.
For instance, we write
const s = text.replace(/[W_]+/g, " ");
to call text.replace
with a regex that matches all non-word characters and underscores with W
and _
respectively.
The g
flag lets us match all instances of the characters.
And then we replace them all with spaces.
Conclusion
To replace all non alphanumeric characters, new lines, and multiple white space with one space with JavaScript, we can use the string replace
method with a regex.