Get all characters not matching a Reg expression pattern in Javascript
I have below requirements where the entered text should match any of the below char lists and get all characters not matching the reg exp pattern.
- 0-9
- AZ, a-d
And special characters like:
- ...
- space, @ -_ & () '/ * = :;
- carriage return
- end of line
A regex I could build like below
/[^a-zA-Z0-9\ \.@\,\r\n*=:;\-_\&()\'\/]/g
In this example, let's say input='123.@&-_()/*=:/\';#$%^"~!?[]av'
. Invalid characters are '#$%^"~!?[]'
.
Below is the approach I used to get the characters not matching.
1) Construct the negation of the allowed pattern regnn as shown below.
/^([a-zA-Z0-9\ \.@\,\r\n*=:;\-_\&()\'\/])/g
(please fix if this is reg exp correct?)
2) Use replace function to get all characters
var nomatch = '';
for (var index = 0; index < input.length; index++) {
nomatch += input[index].replace(/^([a-zA-Z0-9\ \.@\,\r\n*=:;\-_\&()\'\/])/g, '');
}
so nomatch='#$%^"~!?[]' // finally
But here the replace function always returns one unmatched character. so use a loop to get everything. If the input signal is 100 characters, then it loops 100 times and is unnecessary.
Is there a better approach so that all characters don't match the reg exp pattern in the following lines.
- Better regex for getting invalid characters (than the reg exp negation I used above)?
- Avoid unnecessary loops?
- One line approach?
Thanks a lot for any help on this.
source to share
You can simplify it with a reverse regex and replace all valid characters with an empty string so that only invalid characters are left in the output .:
var re = /[\w .@,\r\n*=:;&()'\/-]+/g
var input = '123.@&-_()/*=:/\';#$%^"~!?[]av'
var input = input.replace(re, '')
console.log(input);
//=> "#$%^"~!?[]"
Also note that many special characters do not need to be escaped within a character class.
source to share