JavaScript逐字比较两个句子,如果两个子句彼此为子串,则返回

这里的想法是将两个字符串作为输入,如果a是b的子字符串或b是a的子字符串,则返回true,否则返回false。

例如-

isSubstr(‘hello’, ‘hello world’) // true
isSubstr(‘can I use’ , ‘I us’) //true
isSubstr(‘can’, ‘no we are’) //false

因此,在该函数中,我们将检查较长的字符串,一个字符串包含更多字符,并检查另一个字符串是否是其子字符串。

这是这样做的代码-

示例

const str1 = 'This is a self-driving car.';
const str2 = '-driving c';
const str3 = '-dreving';
const isSubstr = (first, second) => {
   if(first.length > second.length){
      return first.includes(second);
   }
   return second.includes(first);
};
console.log(isSubstr(str1, str2));
console.log(isSubstr(str1, str3a));

输出结果

控制台中的输出将为-

true
false