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:
Or you could create some nice little re-usable functions: