JavaScript String match() method

The match() method in JavaScript is used to search a string for a specified regular expression, and return an array of matched strings. This method takes a single argument, which is the regular expression to search for in the string. If the regular expression is found, the match() method returns an array of matched strings. If the regular expression is not found, the match() method returns null.

Here is an example of how the match() method works:

const string1 = 'Hello, world!';
const regex1 = /world/gi;

const result = string1.match(regex1);

// the result will be: ['world']

In the code example above, we first declare a string called string1 that contains the text Hello, world!. We also declare a regular expression called regex1 that matches the substring world. We then use the match() method to search the string1 string for the regex1 regular expression. The match() method takes a single argument, which is the regular expression to search for in the string. In this case, we pass in the regex1 regular expression as the argument to the match() method.

As a result of calling the match() method, the result variable will be set to ['world'], which is an array containing the matched string world. If the string1 string did not contain the regex1 regular expression, the result variable would be set to null.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: