Reputation: 1393
What I am trying to do is: Get foobar from an array if it contains foo
I usually just use indexOf, but this time I don't have the exact string and I don't know to make use of the includes function
Here is my code sample:
var array = "Hello world, welcome to the universe.";
var str = array.split(" ");
var foobar = str.indexOf(this.includes("uni"));
Upvotes: 0
Views: 47
Reputation: 58
This should get you the index if that is what you are looking for.
var array = "Hello world, welcome to the universe.";
var str = array.split(" ");
var foobar = str.indexOf(str.find(word => word.includes("uni")));
console.log(foobar);
Upvotes: 0
Reputation: 21672
You can use Array.find()
instead, which returns the first item for which the given predicate returns true
. In the event that no item in the array satisfies the predicate, the result of .find()
will be null
.
var array = "Hello world, welcome to the universe.";
var str = array.split(" ");
var foobar = str.find(word => word.includes("uni")); //Find first word that includes "uni"
console.log(foobar);
Upvotes: 2