Simple RegExp Explanation

Here’s my code


<html>
<body>

<script type="text/javascript">
    var input    = "id=87654 name=Kenny";
    var regid    = new RegExp("id=([0-9]+)");
    var regname  = new RegExp("name=([a-zA-z]+)");
    
    var id   = regid.exec(input);
    var name = regname.exec(input);
    
    document.write(id);
    document.write("<br>");
    document.write(name);

</script>

</body>
</html>

The output is


id=87654,87654
name=Kenny,Kenny

How can I get the output to be


id=87654
name=Kenny

I basiclly want to assign the integer and string to their own variables, but without the comma and dupe values.

Performing regexp.exec returns an array. The 0th item in the array will be text that matches the regular expression. In this case this will be the full “id=87654” and “name=Kenny”. The parentheses are used to delimit the substr matches. In order from left to right these parentheses matches are generally referred to as $1, $2… etc. and they will be in the arrays returned by .exec in items [1], [2], etc. respectively. To reference just the ID and just the name, you want to reference the $1 parentheses match, which is stored in the index 1 element of the array.

See the below code:

<script type="text/javascript">
    var input    = "id=87654 name=Kenny";
    var regid    = new RegExp("id=([0-9]+)");
    var regname  = new RegExp("name=([a-zA-z]+)");
    
    var id   = regid.exec(input);
    var userName = regname.exec(input);
    
    document.write(id[1]);
    document.write("<br>");
    document.write(userName[1]);

</script>

</body>
</html>

I also meant to mention that I was getting weird behavior with the var named “name”. Using trusty old google it looks like “name” is potentially a reserved keyword in javascript, so it’s safer to avoid it. (I used userName instead).

Thank you, benzittlau. I had a feeling that might have been what it was. I was trying userName.[1], but I see now that the period is not used with arrays.