SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Addict
    Join Date
    Oct 2001
    Posts
    359
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Regular Expression help

    Have a string, for example: "foo=bar;foo1=somevalue1;foo2=value2;foo3=anothervalue3"

    But only want to extract certain parts of the string, such as foo1 and it's value (until the semicolon), and foo3 and it's value (until the semicolon).

    Any idea's how to do this? Have tried [foo1|foo3].*; but this might be nowhere near the solution...

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    var s="foo=bar;foo1=somevalue1;foo2=value2;foo3=anothervalue3";

    You can match everything that starts with foo1 or foo3 and an equals sign,
    plus everything til you hit a semicolon (or run out of characters).

    alert(s.match(/\b(foo[13]=[^;]+)+/g));


    /* returned value: (Array)
    foo1=somevalue1,foo3=anothervalue3
    */

  3. #3
    Under Construction silver trophybronze trophy AussieJohn's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    776
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    You could use something like the popular "getUrlParam" method, but slightly modified to your case. This would work well especially if your values are arbitrary but you know which you want to extract.

    Code JavaScript:
    function getParam(name, from){
        var results = new RegExp('[\\?;]' + name + '=([^;#]*)').exec(from);
        if (!results) { return undefined; }
        return results[1] || undefined;
    }

    You can then call it like:

    Code JavaScript:
    var paramString = "foo=bar;foo1=somevalue1;foo2=value2;foo3=anothervalue3";
     
    var foo2 = getParam("foo2", paramString);
    var details = {
    . . web: "afterlight.com.au",
    . . photos: "jvdl.id.au",
    . . psa: "usethelatestversion.com"
    }


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
  •