You could do this:
var invalidChars = str.match(/[^\w ]/g), output = '';
if (invalidChars) {
invalidChars = invalidChars.unique();
var lastInvalidChar = invalidChars.pop();
output = 'You have used the illegal character' + (invalidChars.length > 0 ? 's' : '') + ' ' +
invalidChars.join(', ') + (invalidChars.length > 0 ? ' and ' : '') + lastInvalidChar;
}
Here match
and the regular expression /[^\w ]/g
is used to get all characters that are neither word characters nor a space. The array of matched invalid characters is then cleaned from duplicates using the custom unique
method (see below). Then the last invalid character is removed from the array to append it if necessary with an “and” at the end of the output. The remaining invalid characters (if there are any) are then joined with commas and combined with the last invalid character.
Since JavaScript has no built-in unique
method to remove duplicates, you can use this method:
Array.prototype.unique = function() {
var index = {};
for (var i=0; i<this.length; ++i) {
if (!index.hasOwnProperty(this[i])) {
index[this[i]] = this[i];
}
}
var clean = [];
for (var prop in index) {
if (index.hasOwnProperty(prop)) {
clean.push(index[prop]);
}
}
return clean;
};
Note that this implementation is not type-safe as the values are used as property names and thus turned into strings. So ["3",3].unique()
returns ["3"]
hence "3".toString() === (3).toString()
.