The exec() method returns the output in an array form if the matching string exists else returns the null. This descriptive article will provide a piece of deep knowledge about the JavaScript exec() method with the following outcomes.
– How does the JavaScript exec() method work
– How to use the JavaScript exec() method
How does the JavaScript exec() method work
The JavaScript exec() method searches to find the match of a string in a particular string.
Syntax
The syntax of the exec() method is given as follows:
Here, ‘string’ is a parameter that specifies the string to be searched. The exec() returns the matching string or null value.
How to use the JavaScript exec() method
The JavaScript exec() method is used with the aim of searching for a matching string in a specified string. This section provides a direction to use the exec() method in JavaScript with examples.
Example: How to search a string using the exec() method in JavaScript
The exec() method searches for matching strings and returns the output in an array form.
object = newRegExp( "LinuxHint");
output = object.exec(string);
console.log("Returned value : " + output);
object = newRegExp( "website");
output= object.exec(string);
console.log("Returned value : " + output);
In this example, a string “LinuxHint is a programming website” is passed to an object. The regular expressions are used as objects to search the string. When the function calls, it checks whether the matching string is present or not. If the function finds a matching string it will return the first one(original) or a null value.
The returned output showed that there is a matching string in a function. Therefore the function returned the original strings as ‘LinuxHint’ and ‘website’.
Example: How the exec() method behaves if the string does not match
The exec() method either returns the matching string or the null value. The following code tries to match the characters with the string.
object = RegExp( "language");
output = object.exec(string);
console.log("Returned value : " + output);
In the above code, the string “language” is passed to the RegExp object. It will check if the matching string is present or not. In the object, the parameter value is ‘language’. When the function is call, it will return the output.
The output showed there is not a matching string in the string of the specified object. Therefore the function returned the ‘null’ value.
Conclusion
The exec() method returns the output in an array form if the matching string exists else returns the null. The exec() method is applied on the RegExp object’s output. In this descriptive article, we explained the exec() method in JavaScript. For better understanding, we provided the usage and functionality of the exec() method along with examples.