![](/img/trans.png)
[英]Fastest way to check a string contain another substring in JavaScript?
[英]Check if a substring is contained in a string in Javascript (The Opposite Way)
我不是要 substr、indexOf、includes、substring 函数; 它与"apple".isIncludedIn("apple tree")
正好相反
是否有一个 function 以相反的方式检查通常的检查方式? 如果 substring 包含在 javascript 的字符串中,其中 substring 是操作的 object。
因为我希望能够在没有 null 异常问题的情况下安全检查,因为我知道 substring 但要检查的字符串是一个变量,例如
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”(个人意见)。
只需反转参数和被调用的字符串。 达到
"apple".isIncludedIn("apple tree")
做
"apple tree".includes("apple")
为了也允许nulls
而不抛出,如果您想简洁,请使用可选链接。
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"); }
对于不理解可选链的过时浏览器,就像所有现代语法的使用一样,使用Babel将您的代码自动转换为 ES6 或 ES5 以用于生产。
使用||
运营商将解决您的问题。
(str || '').includes("apple")
如果str
是null
,它会检查''
所以返回 false
如果str
存在,则返回如果字符串包含 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.