SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Mar 2010
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Simple RegExp Explanation

    Here's my code

    HTML 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
    Code:
    id=87654,87654
    name=Kenny,Kenny
    How can I get the output to be
    Code:
    id=87654
    name=Kenny
    I basiclly want to assign the integer and string to their own variables, but without the comma and dupe values.

  2. #2
    SitePoint Member
    Join Date
    Apr 2010
    Posts
    21
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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:

    PHP 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> 

  3. #3
    SitePoint Member
    Join Date
    Mar 2010
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  4. #4
    SitePoint Member
    Join Date
    Apr 2010
    Posts
    21
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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).


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •