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.
//Main String
var string0 = ' ": {"MATHEMATICS": {"status": "start", "can_start": false}, "READING": {"status": "start", "can_start": false}, "WRITING": {"status": "start", "can_start": false" ';
//Substrings
var substringArray = ['"MATHEMATICS": {"status": "start"', '"READING": {"status": "start"', '"WRITING": {"status": "start"'];
//Check if Substrings are found in MainString
for (l = 0; l < substringArray.length; l++) {
if (string0.indexOf(substringArray[l]) > -1) {
logger.info("True");
} else {
logger.info("False");
}
}
4 Answers 4
You can try use Array.every method to check for all the substrings.
An example of code:
var isContainsAllTheParts = substringArray.every(function(substring){
return string0.indexOf(substring) >= 0;
});
Comments
Simply use a variable to count the number of "true"
//Main String
var string0 = ' ": {"MATHEMATICS": {"status": "start", "can_start": false}, "READING": {"status": "start", "can_start": false}, "WRITING": {"status": "start", "can_start": false" ';
//Substrings
var substringArray = ['"MATHEMATICS": {"status": "start"', '"READING": {"status": "start"', '"WRITING": {"status": "start"'];
var matchCount = 0;
//Check if Substrings are found in MainString
for (l = 0; l < substringArray.length; l++) {
if (string0.indexOf(substringArray[l]) > -1) {
logger.info("True");
matchCount++;
} else {
logger.info("False");
}
}
if(matchCount == 3){
//do something
logger.info('I did');
} else {
// do some other thing
logger.info('I did not');
}
2 Comments
Not sure why Telman Ahababov's answer wasn't accepted. I'll explain it in case it wasn't clear enough. I'm also shortening it up a bit more and using the simpler includes() method:
let str = "Here is the string in which we want to find multiple substrings."
let subStrArr = ["Here is", "which we", "multiple"]
let containsAllSubStrs = subStrArr.every(subStr => {
return str.includes(subStr);
});
if (containsAllSubStrs) {
//containsAllSubStrs equals 'true', meaning all substrings were found.
} else {
//containsAllSubStrs equals 'false', meaning NOT all substrings were found.
}
Comments
I figured out a way to do it.
var magicNumber = 0;
//Check if Substrings are found in string0
for (l = 0; l < substringArray.length; l++) {
//logger.info(substringArray[l]);
if (string0.indexOf(substringArray[l]) > -1) {
logger.info("True");
magicNumber++;
} else {
logger.info("False");
}
}
while (magicNumber < 3) {
//execute this
}