You are here:   HomeJava ScriptJavascript StringJavaScript SubString
by Dinesh Thakur Category: Javascript String

JavaScript Match() Method compares a regular expression and a string to see whether they match. It returns an array containing one or more matches, depending on how it is used. If no match is found, it returns –1.

 

Syntax for JavaScript Match() Method is:

 

string.match(regex);

 

       The string will be your string literal, and regex will be your regular expression literal. Note the difference in the order between JavaScript Match() Method and the test() method. You could use it in this way:

 

For instance, if you have the string “I am Ironman!” and you match for the substring “Iron”, you want to know that the string contains “Iron” but also where “Iron” occurs. You can perform this type of match with the JavaScript Match() Method of the string object.

 

To perform this match is simple. If “I am Ironman!” is stored in the variable mystring, you would match for “Iron” with the following example of JavaScript Match() Method:

mystring.match(“Iron”);

 

1. Open a new HTML document in your preferred HTML or text editor.

2. Create the body of the document with opening and closing body tags: 

<body>

</body>

3. Insert a script block in the body of the document:

<script language=”JavaScript”>

<!--

// -->

</script>

4. Create a variable named mystring and assign the value “I am Ironman!” to it:

var mystring = “I am Ironman!”;

Display the results of the JavaScript Match() Method so that the final page looks like

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

<title>JavaScript Match() method </title>

</head>

<body>

<h1 style="color: blue">JavaScript Match() Method</h1>

<hr />

<script type="text/javascript">

var mystring = "I am Ironman!";

var tomatch = /Iron/;

if (mystring.match(tomatch)) {

window.alert("Your string contains Iron!");

}

else {

window.alert("Sorry, no Iron in your string.");

}

</script>

</body>

</html>

 

Save the file and close it.

5. Open the file in a browser. You should see the number 5 displayed in the browser as in Figure

JavaScript Match() Method



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.



What's New and Popular





Search Content







Advance Courses



Basic Courses



Advertise with Us