Keep alphanumeric characters and spaces only
Given a text String containing special characters, the following preserves only alphanumeric characters and spaces.
const text = "$#this !text. has() lots<> of }special| characters";
const newText = text.replace(/[^\w\s]/gi, '');
console.log(newText);
// output: this text has lots of special characters
...
Explanation
The replace()
method can be used to replace specific patterns in a given text. Also, this can be used with Regular Expressions (RegExp). In the scenario above, the following tokens are applied:
[^...]
: This is an inverse group of characters. The RegExp engine will search for anything that is not defined within the square brackets.\w
: This is a metacharacter that can match words composed by a sequence of characters, includinga-z
,A-Z
,0-9
, and underscore (_
).\s
: This is a metacharacter that can match different whitespaces characters, including a regular space, a tab, a carriage return, a new line, a vertical tab and a form feed character.g
: This is a modifier indicating that the search will be performed using a global match (finds all possible matches).i
: This is a modifier indicating that the search will be performed in a case-insensitive way.- The final expression is
/[^\w\s]/gi
.
This was a quick overview of how to remove special characters from a text String using JavaScript and Regular Expressions. Check other entries for more information!