I have multiple sub-strings that I want to find in a single string and if all three are found then do this, if not, do something else.
I am kind of stuck on how to set it so that if I get three “True”, I want to execute something, other I want it to do something else.
Many thanks.
My code is below.
JavaScript
x
15
15
1
//Main String
2
var string0 = ' ": {"MATHEMATICS": {"status": "start", "can_start": false}, "READING": {"status": "start", "can_start": false}, "WRITING": {"status": "start", "can_start": false" ';
3
4
//Substrings
5
var substringArray = ['"MATHEMATICS": {"status": "start"', '"READING": {"status": "start"', '"WRITING": {"status": "start"'];
6
7
//Check if Substrings are found in MainString
8
for (l = 0; l < substringArray.length; l++) {
9
if (string0.indexOf(substringArray[l]) > -1) {
10
logger.info("True");
11
} else {
12
logger.info("False");
13
}
14
}
15
Advertisement
Answer
Simply use a variable to count the number of “true”
JavaScript
1
25
25
1
//Main String
2
var string0 = ' ": {"MATHEMATICS": {"status": "start", "can_start": false}, "READING": {"status": "start", "can_start": false}, "WRITING": {"status": "start", "can_start": false" ';
3
4
//Substrings
5
var substringArray = ['"MATHEMATICS": {"status": "start"', '"READING": {"status": "start"', '"WRITING": {"status": "start"'];
6
7
var matchCount = 0;
8
9
//Check if Substrings are found in MainString
10
for (l = 0; l < substringArray.length; l++) {
11
if (string0.indexOf(substringArray[l]) > -1) {
12
logger.info("True");
13
matchCount++;
14
} else {
15
logger.info("False");
16
}
17
}
18
19
if(matchCount == 3){
20
//do something
21
logger.info('I did');
22
} else {
23
// do some other thing
24
logger.info('I did not');
25
}