0

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'.

pilchard
  • 12,414
  • 5
  • 11
  • 23
  • 2
    `str1` does not include `str2`. `includes` tests for a [substring](//en.wikipedia.org/wiki/Substring). You’re looking for a [subsequence](//en.wikipedia.org/wiki/Subsequence) test, instead. – Sebastian Simon Dec 18 '22 at 21:46
  • How exactly is `str2` supposed to be included in `str1`? What are the criteria? – Pointy Dec 18 '22 at 21:47

1 Answers1

0

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');
}
Nora Söderlund
  • 1,148
  • 2
  • 18