Javascript - Regex - how to filter characters that are not part of a regular expression

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); // something similar to this

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 result

Rajesh 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
+4
source share
2 answers

JS regex POSIX, [:alnum:]. [A-Za-z0-9], ASCII.

, , , [^a-zA-Z0-9_.&\s-].

var s = 'this contains invalid chars like #@';
var res = s.replace(/[^\w\s.&-]+/g, '');
var notallowedchars = s.match(/[^\w\s.&-]+/g);
console.log(res);
console.log(notallowedchars);
Hide result

/[^\w\s.&-]+/g (- /g) (- +), (, , _, \w)), (\s), ., & -.

+1

, -, -_.& ^ []

var str = 'asd.=!_#$%^&*()564';

console.log(
    str.match(/[^a-z0-9\-_.&\s]/gi),
    str.replace(/[^a-z0-9\-_.&\s]/gi, '')
);
Hide result
0

Source: https://habr.com/ru/post/1687557/


All Articles