Search the element of an array in Javascript

We can use the ECMASCRIPT 6 Array.find() method to search for a string element which matches the Regular Expression pattern as shown below!

First create a regular expression which matches the string with space in between words.

let re = /\w+\s\w+/g;

Next is that array we are going to search for.

let arr = ["Hello", "Hello World", "Hello!"];

Finally is the Array.find method which will return the string we are searching for.

let outcome = arr.find(function(value, index, array) {
	if(value.match(re)) {
		return true;
}, re);


Take note that the String.match method will return an array if it manages to find the string within that array but when it is within the if block the entire expression becomes true.

Here is the string we are looking for.

Hello World

Leave a Reply

Be the First to Comment!

Notify of