RegEx to remove symbols
by Matthew Day
JavaScript
// OPTION 1: Hardcode the symbols that need to be removed
var text1 = "?Bla#h i*s a w$%^ord t!@hat soun)()ds ni$%ce."
var re1 = /[~&<>"',!@$%()=+{}\[\]\\\/?#*^:;.-]/g;
let removedChars1 = []
let sanitizedPassword1 = String(text1)
.replace(re1, function(s) {
removedChars1.push(s);
return '';
});
console.log(sanitizedPassword1);
console.log('The characters removed from Option 1 are ', removedChars1);
// OPTION 2: Use a variable to store symbols that may be dynamically generated
var someSymbols = "\[~&<>\"',!@$%()=+{}\\[\\]\\\\/?#*^:;\\-._|\]";
var text2 = "T~e&r<r>y \"w'e,n!t @t$o% (t)h=e+ {s}t[o]r\\e\/ ?t#o* ^b:u;y. s-o_m|e eggs"
var re2 = new RegExp(someSymbols, "g");
let removedChars2 = []
let sanitizedPassword2 = String(text2)
.replace(re2, function(s) {
removedChars2.push(s);
return '';
});
console.log(sanitizedPassword2);
console.log('The characters removed from Option 2 are ', removedChars2);