April 14, 2023

Regular expression to remove special characters javascript

javascript
var texto = "Hello! ¿tocinocode?";
var
textoLimpio = texto.replace(/[^\w\s]/gi, '');
console.log(textoLimpio); // Hello tocinocode

Explanation:

  • The regular expression used is [^\w\s], which means "any character that is not a letter, number, or whitespace." The ^ at the beginning of the expression means "negation", that is, "anything other than this".

  • The g modifier stands for "global", which causes the regular expression to find and replace all matching characters in the string, not just the first match.

  • The modifier i means "case insensitive", which makes the regular expression case insensitive.


The replace() function is used to replace matching characters with an empty string, which is equivalent to removing them.

In the example, the original text string is "Hello! Tocinocode?" and the regular expression removes the special characters, leaving the clean text string that is displayed on the console.