Why does the Regex result have two values?

Asked

Viewed 72 times

8

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

The test of my expression results in only 1 match when I test "20kb", but in this script the array has 2 positions. Why this occurs?

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>

1 answer

9


When you include expressions in parentheses, you form a catch group, signalling that she is interested not only in marriage as a whole but also in that particular passage. The result then brings in the first position the integer string married, and in each subsequent position the capture groups in the order in which they were defined.

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

(?:k|m|g)b$
  • 2

    alternatively [kmg]b$ ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.