How to Use JavaScript to Find Matches in Strings and Arrays

How to Use JavaScript to Find Matches in Strings and Arrays

Determining if a String or Array contains a sub string or set of characters using JavaScript is a common task. Most developers expect a native JavaScript contains method since most languages use contains.

Determining if a String or Array contains a sub string or set of characters using JavaScript is a common task. Most developers expect a native JavaScript contains method since most languages use contains.

As with many things JavaScript is slightly different.

With ES6 JavaScript added the includes method natively to both the Array and String natives. The method returns true or false to indicate if the sub-string or element exists. While true or false may provide the answer you need, regular expressions can check if a sub-string exists with a more detailed answer.

Until recently developers would need to create their own method using either indexOf or a regular expression.

That changed in more recent versions of ECMAScript with the addition of the JavaScript includes method.

`JavaScript includes()

ECAMScript 6 added the includes method to both the String and Array objects natively. This method returns either true or false if the target string is contained within the source string or array.

let sample = "The human body is a remarkably adaptable machine. Even if years and years of neglect have allowed pound after pound of fat to fill out your frame, you can rid yourself of that lard at a much faster rate than you brought it on board. In that sense, time is your side!";

//returns   true

//returns   false

let arr = ["one", "two", "three", "four", "five"];

//returns   true

//returns   false

There is an optional fromIndex parameter you can add to indicate the first position the includes method should search.

sample.includes("year", 100);
//returns   false

If a negative fromIndex value is supplied the source string or array is searched from position 0.

For arrays, the search value must match an element, You can't match a substring of an element.

JavaScript Includes Method Compatibility

The good news is browsers have good coverage of the JavaScript includes method. The only browser you need to worry about is Internet Explorer and old and deprecated NodeJs instances. You may also find a few legacy Android browsers hanging around.

Array.includes support:

Chrome Edge FireFox Safari Samsung
47 14 32 9 Yes

Even though Chrome supports the includes method you should know the Google spider uses Chrome 42 to evaluate pages. This means you need to have a polyfil available if your code uses this method.

String.includes support:

Chrome Edge FireFox Safari Samsung
41 Yes 40 9 Yes

JavaScript String Contains Polyfil

There are always polyfils available for modern functionality, well at least most of the time. The JavaScript string includes method is no different.

Part of the ECMAScript project includes the official polyfil. You can add it to a script to dynamically load if needed.

This is the official JavaScript string includes polyfil.

if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {

      if (this == null) {
        throw new TypeError('"this" is null or not defined');

      // 1. Let O be ? ToObject(this value).
      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n β‰₯ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      function sameValueZero(x, y) {
        return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        if (sameValueZero(o[k], searchElement)) {
          return true;
        // c. Increase k by 1. 

      // 8. Return false
      return false;

The string polyfil is simpler:

if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';
    if (typeof start !== 'number') {
      start = 0;
    if (start + search.length > this.length) {
      return false;
    } else {
      return this.indexOf(search, start) !== -1;

Before you go an include the polyfil by default you should feature detect to determine if the script needs to be loaded.

The key to detecting support is the first line of the polyfil:

if (!Array.prototype.includes) {
    //load includes polyfil
Finding a Sub-String Using indexOf

The first old school way to identify if a string or array contains a string is using the indexOf method. If the string or array contains the target string the method returns the first character index (string) or item index (Array) of the match.

If there is no match found indexOf returns -1. This is because arrays are zero indexed in JavaScript, so -1 means the value does not exist.

function contains(src, test){

    return src.indexOf(test) !== -1;    

The method returns true if the target string exists and false if it doesn't.

Using Regex to Determine if a Sub-String Exist

The indexOf method is pretty basic, but not the most flexible technique. I prefer using regular expressions because you can craft all sorts of patterns.

The main advantage regular expressions have is they are not limited to a single string. Regular expressions utilize a pattern, which means you can match multiple items in a string or array. This works great for parsing data, a common business scenario.

There are also multiple native regex methods to test for the presence of a string pattern.

The search method works like the indexOf method. It returns the first position a match is found. If no match is found -1 is returned.

var src = "foo",
    expr = /oo/;;

The next method is match. This works differently than the other methods because it returns an object representing the match.


    0: "years",
    groups : undefined,
    index : 58,
    input : "The human body is a remarkably adaptable machine. Even if years and years of neglect have allowed pound after pound of fat to fill out your frame, you can rid yourself of that lard at a much faster rate than you brought it on board. In that sense, time is your side!",
    length : 1

The match object includes the index where the match was found. It also includes the original test string or array.

The interesting thing is when you modify the regular expression with the global modifier (g) the method returns an array of the matched values, not the full match object.



The downside to using match is it only works on strings, not arrays.

The last regular expression method is test. This works very differently than the other methods.

Here you call test from the regular expression pattern and supply the source string. If there is a match in the source string the method returns true. If there is no match it returns false.


//returns true


//returns false

The downside to this method is lack of detail. It does provide true or false about a match, but you do not know where the match was found or how many were found. It is a simple test.


You can safely use the JavaScript includes method for both Arrays and Strings today. But like most modern APIs you should do feature detection in the browser to determine if a polyfil should be loaded. For the most part this won't be an issue unless a user happens to be using Internet Explorer. And since IE should only be limited to use with legacy web applications in enterprises the chances of encountering a browser not supporting includes is slim.

The includes method only returns true or false is the criteria exists in the array or string. If you need to know the match index or indexes you should revert to either indexOf or a more advanced regular expression.

Thank you for reading! Share this Article with Your Friends!

JavaScript Array.flatMap()

JavaScript Array.flatMap()

JavaScript Array.flatMap(): Use flatMap to map over an array and flatten the result array in one go! Now lets up the game and introduce "flatMap". It combines the steps of first mapping over the array with `map()` & then calling `flat()`. Instead of calling 2 methods, just use `flatMap()` πŸ‘

Now lets up the game and introduce "flatMap". It combines the steps of first mapping over the array with map() & then calling flat(). Instead of calling 2 methods, just use flatMap() πŸ‘

const foods = ['🍫', '🍦'];

// ❌ map + flat => [food, 'πŸ˜‹']).flat();

// βœ… flatMap
foods.flatMap(food => [food, 'πŸ˜‹']);

// Result
// ['🍫', 'πŸ˜‹', '🍦', 'πŸ˜‹']

How flatMap() works?

Let's go through step-by-step what flatMap() is doing. I was a bit confused when I first learned this one. Cause I thought it flattens and then it does the mapping. But no πŸ™…. It first map() and then it flat().

const names = ['jane', 'john'];

// Step 1: map
const nestedArray =, index) => [name, index]);
// [ ['jane', 1], ['john', 2 ] ]

So now we have a nested array. And we can use flat() to flatten the array.

const nestedArray = [
  ['jane', 1],
  ['john', 2]

// [ 'jane', 1, 'john', 2 ]

Of course, we can shorten this and just call flatMap(). Let's take a look πŸ‘€

const names = ['jane', 'john'];

const result = names.flatMap((name, index) => [name, index]);

// [ 'jane', 1, 'john', 2 ]

And Voila! We have the same result πŸ‘

flatMap only flattens 1-level deep

With flat(), it accepts a parameter where you set the depth. What this means is you can specify how deep a nested array should be flattened.

const depth1 = [[1], [2]];
depth1.flat(); // same as depth.flat(1)
// [1, 2]

const depth2 = [[[1, 2]]];
// [1, 2]

Now for flatMap(), you can only go 1-level deep.

const names = ['jane'];

names.flatMap((name, index) => [[name, index]]);
//  [ ['jane', 1] ]

Let's break this into 2 steps, so you can see what's going on.

const names = ['jane'];

// Step 1: created a 2-level deep array
const twoLevelDeep =, index) => [[name, index]]);
// [ [ ['jane', 1] ] ]

// Step 2: flat using depth 1
//  [ ['jane', 1] ]

But if you do it separately, I can pass a depth parameter and flatten it completely:

// [ 'jane', 0, 'john', 1 ]

So, if you want it to flatten beyond depth of 1. Then it is better to NOT use flatMap() and just call the methods separately πŸ‘

flatMap to filter item

One really cool you can do with flatMap is to remove an element. In this example, I want to remove all negative numbers.

const numbers = [1, 2, -3, -4, 5];

numbers.flatMap(number => {
  return number < 0 ? [] : [number];

// [ 1, 2, 5]

That's really cool! It's like acting like a filter. But how is this actually working. The secret is the empty array. Let's see what I mean.

const emptyNestedArray = [[], 1];

// [ 1 ]

When you try to flatten an element that's an empty array, it simply removes that item. So we can use that knowledge to make flatMap act kind of like filter method. Neat right! πŸ‘


Originally published at

JavaScript array : How to merge two arrays in JavaScript

JavaScript array : How to merge two arrays in JavaScript

In this post, We go over how to merge two arrays in JavaScript using the concat method and the spread syntax.

Array Concat() method

The concat method is used to merge two arrays. As a result, it returns a new array instead of modifying the existing array.

Let’s look at an example using the concat method. We have two arrays named fruits1 and fruits2. They both contain strings that correspond to a fruit.

const fruits1 = ['apple', 'banana', 'grapes'];
const fruits2 = ['melons', 'watermelon'];

const combinedFruits = fruits1.concat(fruits2);

console.log(combinedFruits); //[ 'apple', 'banana', 'grapes', 'melons', 'watermelon' ]

Array Spread syntax

Now let’s look at an example using the spread syntax.

const fruits1 = ['apple', 'banana', 'grapes'];
const fruits2 = ['melons', 'watermelon'];

const combinedFruits = [...fruits1, ...fruits2];

console.log(combinedFruits); //[ 'apple', 'banana', 'grapes', 'melons', 'watermelon' ]

In this example, we created a new array and assigned it to the variable combinedFruits. We then took the two fruits array and used the spread them out in the array. We used the ... syntax to spread out the contents of the fruits array into the new array.

Thanks for reading !

All about JavaScript Arrays Methods

All about JavaScript Arrays Methods

Everything You Need to Know About JavaScript Array Methods

Web development or web programming gave birth to dynamic web applications. With the rise of the web, JavaScript has become one of the most important languages in today’s world. This **JavaScript Array **article will take you to the depths of array methods in JavaScript in the following sequence:

  • Introduction to JavaScript
  • Fundamentals of JavaScript
  • JavaScript Array
  • Difference between Array and Objects
  • JavaScript Array Methods
Introduction to JavaScript

JavaScript is a high level, interpreted, programming language used to make web pages more interactive. It is a very powerful client-side scripting language which makes your webpage more lively and interactive.

It is a programming language that helps you to implement a complex and beautiful design on web pages. If you want your web page to look alive and do a lot more than just gawk at you, JavaScript is a must.

Fundamentals of JavaScript

If you are new to the language, you need to know some of the fundamentals of JavaScript that will help you start writing your code. The basics include:

JavaScript Array

An array is a data structure that contains a list of elements which store multiple values under a single variable.

To declare an array in JavaScript use the β€˜let’ keyword with square brackets and enclose all the elements within them. The syntax is as follows:

let ListItems=[];

You can also declare it as:

let ListItems=['shoes','watch','bag'];

Difference between Array and Objects

JavaScript variables can be objects. Arrays are considered to be special kinds of objects. Because of this, you can have variables of different types in the same Array.

myArray[0] =;
myArray[1] = myFunction;
myArray[2] = myItems;

In JavaScript, arrays use numbered indexes. Whereas, objects are used as named indexes.

JavaScript Array Methods

The purpose of using an array is to store** multiple values** in a single entity of a declared variable. Arrays are used when we want to access elements in an orderly fashion using a single variable. One can store strings, boolean and numbers in a single array.

There are different JavaScript array methods in order to perform various tasks such as:
push() – It is easy to remove elements and add new elements while working with arrays. The push() method adds a new element to the end of an array. The return value is the new array length.

let listItems = ['bag','shoes','dress'];



Push() doest not return the value that has been added to the array. It only returns the new length of the array.
**pop() – **The pop() method is used to remove the last element from an array. It returns the value that has been popped out.

let listItems = ['bag','shoes','dress'];



Pop() returns the value that has been removed and not the array length like Push().
shift() – Shifting is similar to popping, working on the first element instead of the last. The shift() method is used to remove the first array element and shifts all other elements to a lower index. It will return you the string that has been shifted out.

let listItems = ['bag','shoes','dress'];



Shift() works same as pop() but it returns the first element of the array instead of the last one.
unshift() – The unshift() method adds a new element at the beginning of an array and unshifts older elements. It is similar to Push() and returns the new array length.
**Example: **

let listItems = ['bag','shoes','dress','watch'];



Unshift() will add the new element into the array and return the length of the new array.
concat() – The concat() method creates a new array by concatenating or merging existing arrays. It does not modify the existing array and always returns a new array.

let arr1 = ['red','blue','green'];
let arr2 = ['colors','spraypaint', 'brush'];
let newArr = arr1.concat(arr2);


toString() – The toString() method is used to convert an array to a string of array values, separated by commas.

let colors = ['red','blue','green'];



join() – The join() method works same as toString(). It is used to join all array elements into a string, but in addition, you can specify the separator.

let colors = ['red','blue','green'];



reverse() – The reverse() method is used to reverse the order of the elements in an array. It will change the original array and swap the order of the elements.

let fruits = ['mango','apple','grapes'];


sort() – The sort() method is used to sort an array alphabetically. This function sorts the values as string by default.

let fruits = ['mango','apple','grapes'];


slice() – The slice() method is used to slice out a piece of an array into a new array. It creates a new array without removing any elements from the source array. It will return the value that has been sliced out from the array.

let colors = ['red','blue','green','yellow','orange'];


These were some of the most commonly used JavaScript array methods. With this, we have come to the end of our article. I hope you understood how array methods are used in JavaScript.