Skip to content
Advertisement

Javascript – How to check if a string contains multiple substrings

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");
  }
}

Advertisement

Answer

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');
  }
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement