3

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.

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

I don't think we need to use map to construct the RegExp because the required char's are predefined (see my question). I can safely construct the RegExp = /(?=.*c)(?=.*f)(?=.*o)(?=.*v)/
Yes absolutely you can use /(?=.*c)(?=.*f)(?=.*o)(?=.*v)/ if it is predefined search string. I guess I focussed on the side that search string can be dynamic and not known in advance.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.