JavaScript match

The JavaScript match string function is used to search for a specified string and return the array of matched substrings. The syntax of the JavaScript match string function is

  • String_Object: Original string to perform a search. It check for a portion of a string present in this String_Object
  • RegExp: Valid str or Regular expression you want to look. If the specified substring is not in the string_object, it will return NULL

JavaScript match Example

The following set of examples will help you understand the JavaScript match string function. The first three statements are useful to declare three string variables.

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

Next, we used a regular expression to search for ‘abc’ substring globally. So, JavaScript match function returns every occurrence of ‘abc’ to output. From the below image and this statement, you can observe that the term abc repeated many times. However, the JS match function considers the “ABC” is different from “abc” and “Abc”.

Now, let us use the i regular expression along with it (i will perform the case insensitive string search.)

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

<!DOCTYPE html>
    <title> JavaScriptMatch </title>
    <h1> JavaScriptMatch </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