I want to accept words and some special characters, so if my regular expression does not fully match, let's say I show an error,
var re = /^[[:alnum:]\-_.&\s]+$/;
var string = 'this contains invalid chars like #@';
var valid = string.test(re);
but now I want to "filter out" the phrase by deleting all characters that do not match the regular expression?
Usually one of them is used, but how to list all characters that do not match the regular expression?
var validString = string.filter(re);
how to do it?
considers
Wiktor Stribiżew's solution works great:
regex=/[^a-zA-Z\-_.&\s]+/g;
let s='some bloody-test @rfdsfds';
s = s.replace(/[^\w\s.&-]+/g, '');
console.log(s);
Run codeHide resultRajesh solution:
regex=/^[a-zA-Z\-_.&\s]+$/;
let s='some -test @rfdsfds';
s=s.split(' ').filter(x=> regex.test(x));
console.log(s);
Run codeHide result
source
share