Reddy
Reddy

Reputation: 1453

Test if all given char's are in string - Javascript

I'm looking for smart, fast and simple way to check if the string contains all of the predefined char's.

For example:

var required = 'cfov'; //These are the char's to test for.

var obj = {valid: 'vvcdfghoco'}; //Valid prop can contains any string.

//what I have so far::
var valid = obj.valid, i = 0;
for(; i < 4; i++) {
  if(valid.indexOf(required.chatAt(i)) === -1) {
     break;
  }
}
if(i !== 3) {
  alert('Invalid');
}

Can we do it in RegExp? if yes, any help plz!

Thanks in Advance.

Upvotes: 3

Views: 60

Answers (2)

user4227915
user4227915

Reputation:

You can do this way:

var required = 'cfov'; //These are the char's to test for.


var valid = 'vvcdfghoco'; //Valid prop can contains any string.

var regex = new RegExp("^[" + valid + "]*$");
/* this line means: 
     from start ^ till * the end $ only the valid characters present in the class [] */


if (required.match(regex)) {
  document.write('Valid');
}
else {
  document.write('Invalid');
}

Hope it helps.

Upvotes: 1

anubhava
anubhava

Reputation: 784898

You can build a lookahead regex for your search string:

var re = new RegExp(required.split('').map(function(a) {
          return "(?=.*" + a + ")"; }).join(''));
//=> /(?=.*c)(?=.*f)(?=.*o)(?=.*v)/

As you note that this regex is adding a lookahead for each character in search string to make sure that all the individual chars are present in the subject.

Now test it:

re.test('vvcdfghoco')
true
re.test('vvcdghoco')
false
re.test('cdfghoco')
false
re.test('cdfghovco')
true

Upvotes: 3

Related Questions