Legionar Legionar - 3 months ago 6
Javascript Question

How to return incorrect characters?

I am using JavaScript to check, if a string contains invalid characters; allowed characters are

a-z
,
A-Z
,
0-9
and
-
:

var str = 'Some string!',
invalid_characters = [];

if (/^[a-zA-Z0-9-]*$/.test(str) == false) {
console.log('Invalid characters: ' + invalid_characters.join(', '));
}
else {
console.log('String is OK.');
}


So in the exaple above,
and
!
are incorrect. How can I get these characters to the array
invalid_characters
(each character only once without duplicates)? Thanks.

Answer

Filter out the characters that don't comply with your pattern.

var str = 'Some string!!!';

var invalid_characters = str.split('').filter(function(char){
    return !/[a-zA-Z0-9-]/.test(char)
})

// Filtering out duplicates
invalid_characters = invalid_characters.filter(function(char, pos) {
    return invalid_characters.indexOf(char) == pos;
})

console.log(invalid_characters) //[" ","!"]