简体   繁体   中英

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

I'm not asking for substr, indexOf, includes, substring functions; it's the opposite of that like "apple".isIncludedIn("apple tree")

Is there a function that checks the other way around the usual way of checking? If a substring is contained in a string in javascript where the substring is the object of action.

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

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

[Additional Note]

I'm aware that I can do (str && str.includes()) or ((str || '').includes()) but these seem "hacky" to me (personal opinion).

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.

Using || operator will solve your issue.

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

If str is null , it checks with '' so returns false

If str is present, it returns if string contains substring

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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