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

更新於: 2020 年 8 月 24 日

126 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始體驗
廣告
© . All rights reserved.