Why does the RegEx result have two values?

8

I need kb, mb or gb patterns, I'm using the regular expression (k|m|g)b$ and it has to be at the end of the line.

test my expression results in only 1 match when testing "20kb", but in this script the array has 2 positions. Why does this occur?

Script

<!DOCTYPE html>
<html>
<body>


<p id="p01">The best things in life are free!</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    text = document.getElementById("p01").innerHTML; 
var re = "(k|m|g)b$";
var str = "20kb".trim().toLowerCase();
var myArray = str.match(re);
console.log(myArray);
   document.getElementById("demo").innerHTML = myArray;
}

</script>

</body>
</html>
    
asked by anonymous 24.04.2015 / 20:35

1 answer

9

When you include expressions in parentheses, you form a catch group , signaling that you are interested not only in the marriage as a whole but also in that particular passage. The result then brings the entire string into the first position, and at each subsequent position the catching groups in the order they were defined.

To make a group not capture, use (?:...) :

(?:k|m|g)b$
    
24.04.2015 / 20:40