Amit Shah
Amit Shah

Reputation: 61

Need Regex that check at least 4 different character in string

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.

Upvotes: 5

Views: 379

Answers (3)

gayavat
gayavat

Reputation: 19398

var str = "abcdef"
var counter = 0; 
hash = new Object(); 
var i;
for(i=0; i< str.length; i++){
  if(!hash[str.charAt(i)]){
    counter +=1; hash[str.charAt(i)]=true
  }
}

if(counter < 4){
  console.log("error");
}

Upvotes: 0

Chris Pitman
Chris Pitman

Reputation: 13104

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

Upvotes: 1

jfriend00
jfriend00

Reputation: 707456

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/

Upvotes: 6

Related Questions