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

2
  • 2
    str1 does not include str2. includes tests for a substring. You’re looking for a subsequence test, instead. Commented Dec 18, 2022 at 21:46
  • How exactly is str2 supposed to be included in str1? What are the criteria? Commented Dec 18, 2022 at 21:47

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.