Phil
Phil

Reputation: 758

Javascript - Regex - how to filter characters that are not part of regex

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);

Upvotes: 5

Views: 6899

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626754

JS regex engine does not support POSIX character classes like [:alnum:]. You may use [A-Za-z0-9] instead, but only to match ASCII letters and digits.

Your current regex matches the whole string that contains allowed chars, and it cannot be used to return the chars that are not matched with [^a-zA-Z0-9_.&\s-].

You may remove the unwanted chars with

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);

The /[^\w\s.&-]+/g pattern matches multiple occurrences (due to /g) of any one or more (due to +) chars other than word chars (digits, letters, _, matched with \w), whitespace (\s), ., & and -.

Upvotes: 1

Justinas
Justinas

Reputation: 43481

To match all characters that is not alphanumeric, or one of -_.& move ^ inside group []

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

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

Upvotes: 0

Related Questions