I have a special validation need where I need to check if a string contains ANY out of several substrings like the following list:
12
23
34
45
56
67
78
89
90
01
I am new to jQuery and the only thing I could think of here is the following which doesn't look good to me:
if(str.indexOf("12") >= 0 || str.indexOf("23") >= 0 || str.indexOf("34") >= 0 || str.indexOf("45") >= 0 || str.indexOf("56") >= 0 || str.indexOf("67") >= 0 || str.indexOf("78") >= 0 || str.indexOf("89") >= 0 || str.indexOf("90") >= 0 || str.indexOf("01") >= 0){
// do stuff
}
Is there a better way where I can compare a string against multiple substrings, e.g. using Regex or arrays ? In addition, I would also need to count the number of matches for which I didn't find an approach.
Many thanks in advance for any help with this.
You could convert this to a slightly more maintainable format, without getting into regular expressions. This is one way to use an array to accomplish your goal:
var str = '2042038423408';
// Super-quick one-liner (split here for visibility)
var matchCount = $.grep(['12', '23', '34', '45', '56', '67', '78', '89', '90', '01'], function(num, i) {
return str.indexOf(num) !== -1;
}).length; // should be 2
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Or you could create some nice little re-usable functions:
var valuesToCheck = ['12', '23', '34', '45', '56', '67', '78', '89', '90', '01'];
// Pure JavaScript
function howManyMatches(testString) {
var matches = 0;
for (var valueIndex = 0; valueIndex < valuesToCheck.length; valueIndex++) {
if (testString.indexOf(valuesToCheck[valueIndex]) !== -1) {
matches++;
}
}
return matches;
}
// Here's the jQuery version again
function howManyMatches2(testString) {
return $.grep(valuesToCheck, function(num, i) {
return testString.indexOf(num) !== -1;
}).length;
}
// Usage
var letsTest = howManyMatches('282982902090229892');
var letsTest2 = howManyMatches2('282982902090229892');
console.log('JavaScript: ' + letsTest); // 2
console.log('jQuery: ' + letsTest2); // 2
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>