Skip to content

Array match JavaScript | Examples

  • by

If you are looking for a match string against the array then use regular expressions or some() method in JavaScript.

About creating a regular expression on the fly when you need it (assuming the array changes over time)

if( (new RegExp( '\\b' + array.join('\\b|\\b') + '\\b') ).test(string) ) {

For browsers that support javascript version 1.6, you can use the some() method

if ( array.some(function(item){return (new RegExp('\\b'+item+'\\b')).test(string);}) ) {

Array match JavaScript

Simple example code.

<!DOCTYPE html>
   var str = "the word tree is in this sentence"; 
   var arr = [];
   array[0] = "dog";  
   array[1] = "cat";  
   array[2] = "bird";  
   array[3] = "birds can fly";  

   if( (new RegExp( '\\b' + arr.join('\\b|\\b') + '\\b') ).test(str) ){
    console.log('Match'); }
      console.log('No match');



Array match JavaScript


How can I find matching values in two arrays?

Answer: Use the filter() and includes() method for it.

    var a1 = ["cat", "sum","fun", "run"];
    var a2 = ["bat", "cat","dog","sun", "hut", "gut"];

    const intersection = a1.filter(element => a2.includes(element));


Output: [ “cat” ]

Do comment if you have any doubts or suggestions on this Js Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *