首页 > 解决方案 > 检查子字符串是否包含在Javascript中的字符串中(相反的方式)

问题描述

不是要 substr、indexOf、includes、substring 函数;与此相反"apple".isIncludedIn("apple tree")

是否有一个功能可以检查通常的检查方式的另一种方式?如果子字符串包含在 javascript 中的字符串中,其中子字符串是操作的对象。

因为我希望能够在我知道子字符串但要检查的字符串是变量的情况下安全地检查而不会出现空异常问题,例如

let arr = [null, "apple tree"]
let str = arr[Math.floor(Math.random() * arr.length)];
if ("apple".isIncludedIn(str)) {
  console.log("It is!");
}

因为str.includes("apple")会导致Cannot read property 'includes' of null

[附加说明]

我知道我可以做到,(str && str.includes())或者((str || '').includes())但这些对我来说似乎“hacky”(个人意见)。

标签: javascriptstring

解决方案


Just reverse the argument and the string being called on. To achieve

"apple".isIncludedIn("apple tree")

do

"apple tree".includes("apple")

To also permit nulls without throwing, use optional chaining if you want to be concise.

let arr = [null, "apple tree"]
let str = arr[Math.floor(Math.random() * arr.length)];
if (str?.includes("apple")) {
  console.log("It is!");
} else {
  console.log("It's not");
}

For obsolete browsers that don't understand optional chaining, just like all uses of modern syntax, use Babel to transpile your code down to ES6 or ES5 for production automatically.


推荐阅读