JavaScript 逐字比较两个句子,并返回它们是否是彼此的子字符串
javascriptweb developmentobject oriented programming更新于 2025/10/3 10:20:17
这里的想法是将两个字符串作为输入,如果 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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

