Parentheses in regex

Parentheses in regex
0

#1

hello,

i am using a match() function to find a - .* in a string

when i write the code with parentheses i get in the log an array with 2 elements but when i use without parentheses the match function create an array with one element?

This is the code:

//one element
var str = "the kid is amazing";
            
            console.log(str.match(/.*/));

// 2elements 

var str = "the kid is amazing";
            
            console.log(str.match(/(.*)/));


#2

According to the match documentation:

If the string matches the expression, it will return an Array containing the entire matched string as the first element, followed by any results captured in parentheses. If there were no matches, null is returned

In the first example, it is just going to return the array of the entire matched string (only one element). In the second example, it is going to return an array with the first element being the entire matched string of “the kid is amazing” and the second element containing the result captured in the one set of parentheses which is “the kid is amazing”.


#3

Thanks Randell, you explained it perfectly!.