JavaScript match

The JavaScript match string function searches for a specified string and returns the array of matched substrings. The syntax of the JavaScript match string function is

String_Object.match(RegExp)
  • String_Object: Original string to perform a search. It checks for a portion of a text 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 for declaring three string variables.

The following statement will search for ‘abc’ and return it. As you can see, ‘abc’ substring is 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, the JavaScript match function returns every occurrence of ‘abc’ to output. From the below image and this statement, you can observe that the term abc is repeated many times. However, the JS match function considers the “ABC” is different from “abc” and “Abc”.

Now, let us use 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>
<html>
<head>
    <title> JavaScriptMatch</title>
</head>
<body>
    <h1> JavaScriptMatch</h1>
<script>
    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 \>");
    document.write(Str7);
</script>
</body>
</html>
JavaScript MATCH Function