JavaScript Match

The JavaScript Match function is one of the String Functions. This JavaScript string match function is used to search for a specified string and return the array of matched substrings. The syntax of the string match function in JavaScript is

  • String_Object: String to perform a search. JS Match function check for a portion of a string present in this String_Object
  • RegExp: Valid string or Regular expression you want to match. If the specified substring is not in the string_object, the Match function will return NULL

JavaScript Match Example

The following set of examples will help you understand the string match function.

<!DOCTYPE html>
    <title> JavaScript Match </title>
    <h1> JavaScript Match </h1>
    var Str1 = "We are ABC working at abc company since Abc years";
    var Str2 = "We are abc working at abc company since Abc years";
    var Str3 = Str2.match("abc");
    var Str4 = Str2.match(/abc/g);
    var Str5 = Str1.match("abc");
    var Str6 = Str1.match(/abc/gi);
    var Str7 = Str1.match("JavaScript");
    document.write(Str3 + "<br \>");
    document.write(Str4 + "<br \>");
    document.write(Str5 + "<br \>");
    document.write(Str6 + "<br \>");
JavaScript MATCH Function

Following statement will search for ‘abc’ and return it. As you can see, ‘abc’ substring repeated thrice in Str2, but the Match String Function is returning the first occurrence

var Str3 = Str2.match("abc");

Next, we used a regular expression to search for ‘abc’ substring globally. So, JavaScript match function returns every occurrence of ‘abc’ to output

var Str4 = Str2.match(/abc/g);

From the above statement, you can observe that the term abc repeated many times. However, the JS Match function considers the string “ABC” is different from “abc” and “Abc”. Now, let us use the i regular expression along with string (i will perform the case insensitive string search.)

var Str6 = Str1.match(/abc/gi);

Finally, we used a non-existing item inside the string match function. As we said before, JavaScript returns NULL as output

var Str7 = Str1.match("JavaScript");