I need Regex that checks if a String
has at least 4 unique characters. For example, if a string is "test"
then it fails because it have three different chars but if a string is "test1"
then it passes.
I'm not sure how to do that with a regex, nor would I expect that to be a good way to solve the problem. Here's a more general purpose function with regular javascript:
function countUniqueChars(testVal) {
var index = {};
var ch, cnt = 0;
for (var i = 0; i < testVal.length; i++) {
ch = testVal.charAt(i);
if (!(ch in index)) {
index[ch] = true;
++cnt;
}
}
return(cnt);
}
function hasFourUniqueChars(testVal) {
return(countUniqueChars(testVal) >= 4);
}
You can see it work here: http://jsfiddle.net/jfriend00/bqBRv/
If you are open to using additional libraries, undescore.js provides some utility functions that can make this a very short and sweet query:
function countUniqueCharacters(value) {
return _.uniq(value.split("")).length;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With