javascript - 检查子字符串是否包含在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”(个人意见)。
解决方案
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.
推荐阅读
- date - 以日期类型为条件的 IFS 公式
- php - 如何在 laravel dom pdf 版本 0.7.0 中添加外部链接
- mysql - 如果同步到 Redshift/BigQuery,来自 MySQL 数据库的 bin 日志复制是否会保持唯一的约束?
- php - 如何自动关闭截断段落中的标签
- search - 禁用谷歌索引网站电话号码
- java - 如何让 Arduino 和 Java 通过单字节进行通信
- hbase - 在 HBase 中,更新记录或删除并插入新记录哪个更快
- android - allDocs之间的区别,在关系袋中找到性能
- ios - 使用蓝牙将数据从 carplay 应用程序传输到 iPhone 应用程序
- flutter - 我需要一个不重复的随机数生成器