Search code examples
javascriptstringcompareinclude

How to compare two string in javascript?


I have two string and want to check if one includes the other. Any ideas how to compare them properly?

let str1 = 'love you too much';
let str2 = 'lo ou to uc';

if (str1.includes(str2)) {
  console.log('str1 includes str2');
} else {
  console.log('str1 does not include str2');
};

When I use the includes method I get the result 'False'.


Solution

  • Given the criteria that each segment in str2 should be split by a whitespace, in where all must be found in str1: Iterate through each segment and use String.includes on each case.

    let str1 = 'love you too much';
    let str2 = 'lo ou to uc';
    
    function stringIncludesSubstrings(haystack, needles) {
      needles = needles.split(' ');
      
      for(let index = 0; index < needles.length; index++) {
        if(!haystack.includes(needles[index]))
          return false;
      }
      
      return true;
    };
    
    if (stringIncludesSubstrings(str1, str2)) {
      console.log('str1 includes str2');
    } else {
      console.log('str1 does not include str2');
    }