简体   繁体   English

检查 Javascript 的字符串中是否包含 substring(相反的方式)

[英]Check if a substring is contained in a string in Javascript (The Opposite Way)

I'm not asking for substr, indexOf, includes, substring functions;不是要 substr、indexOf、includes、substring 函数; it's the opposite of that like "apple".isIncludedIn("apple tree")它与"apple".isIncludedIn("apple tree")正好相反

Is there a function that checks the other way around the usual way of checking?是否有一个 function 以相反的方式检查通常的检查方式? If a substring is contained in a string in javascript where the substring is the object of action.如果 substring 包含在 javascript 的字符串中,其中 substring 是操作的 object。

Because I want to be able to safely check without the null exception issue for the case that I know the substring but the string to check on is a variable, eg因为我希望能够在没有 null 异常问题的情况下安全检查,因为我知道 substring 但要检查的字符串是一个变量,例如

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

Because str.includes("apple") can result to Cannot read property 'includes' of null因为str.includes("apple")可能导致Cannot read property 'includes' of null

[Additional Note] [附加说明]

I'm aware that I can do (str && str.includes()) or ((str || '').includes()) but these seem "hacky" to me (personal opinion).我知道我可以做(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.为了也允许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"); }

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.对于不理解可选链的过时浏览器,就像所有现代语法的使用一样,使用Babel将您的代码自动转换为 ES6 或 ES5 以用于生产。

Using ||使用|| operator will solve your issue.运营商将解决您的问题。

(str || '').includes("apple")

If str is null , it checks with '' so returns false如果strnull ,它会检查''所以返回 false

If str is present, it returns if string contains substring如果str存在,则返回如果字符串包含 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM