I want to accept words and some special characters, so if my regex does not fully match, let's say I display an error,
var re = /^[[:alnum:]\-_.&\s]+$/;
var string = 'this contains invalid chars like #@';
var valid = string.test(re);
but now I want to "filter" a phrase removing all characters not matching the regex ?
usualy one use replace, but how to list all characters not matching the regex ?
var validString = string.filter(re); // something similar to this
how do I do this ?
regards
Wiktor Stribiżew solution works fine :
regex=/[^a-zA-Z\-_.&\s]+/g;
let s='some bloody-test @rfdsfds';
s = s.replace(/[^\w\s.&-]+/g, '');
console.log(s);
Rajesh solution :
regex=/^[a-zA-Z\-_.&\s]+$/;
let s='some -test @rfdsfds';
s=s.split(' ').filter(x=> regex.test(x));
console.log(s);
[:alnum:](you may use[A-Za-z0-9]instead, but only to match ASCII letters and digits). you may try runnings.match(/[^\w\s.&-]/g)to get the chars that do not match letters, digits,_,.,&, whitespace and-.string.split(' ').filter(x => !regex.test(x))