Use the exec of method in JavaScript's regular expressions

  • 2020-06-15 07:36:03
  • OfStack

The exec method searches for the text string for a regular expression match. If a match is found, the result array is returned; Otherwise, return null.
grammar


RegExpObject.exec( string );

Here is the details of the parameters:

string: The string to search for

The return value:

If 1 match is found, if not null, the matching text is returned.

Example:


<html>
<head>
<title>JavaScript RegExp exec Method</title>
</head>
<body>
<script type="text/javascript">
  var str = "Javascript is an interesting scripting language";
  var re = new RegExp( "script", "g" );

  var result = re.exec(str);
  document.write("Test 1 - returned value : " + result); 

  re = new RegExp( "pushing", "g" );
  var result = re.exec(str);
  document.write("<br />Test 2 - returned value : " + result); 
</script>
</body>
</html>

This will produce the following results:


Test 1 - returned value : script
Test 2 - returned value : null 


Related articles: