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) ) {
  alert('match');
}

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);}) ) {
 alert('match');
}

Array match JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
   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'); }
    else{
      console.log('No match');
    }
  </script>

</body>
</html>

Output:

Array match JavaScript

Source: stackoverflow.com

How can I find matching values in two arrays?

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

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

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

    console.log(intersection)
  </script>

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading