user381800
user381800

Reputation:

Javascript Regex with Match

I am trying to extract a number from a string with regular expression as I am told this would be the best approach for what I am wanting to do.

Here is the string:

http://domain.com/uploads/2011/09/1142_GF-757-S-white.jpg&h=208&w=347&zc=1&q=90&a=c&s=&f=&cc=&ct=

and I am trying to extract 208 from (height) from the string. so I know I have to look for "&h=" in the expression but I don't know what to do after that. How can I match between that and the next "&" but not include them as well...

Thanks..

Upvotes: 1

Views: 98

Answers (2)

jfriend00
jfriend00

Reputation: 708136

To get the entire h=xxxx parameter, you can use this generic function (which you can reuse elsewhere for other purposes) and pass it the desired key:

function getParameterFromURL(url, key) {
    var re = new RegExp("[&?]" + key + "=([^&]*)");
    var matches = url.match(re);
    if (matches) {
        return(matches[1]);
    }
    return(null);
}


var url = "http://domain.com/uploads/2011/09/1142_GF-757-S-white.jpg&h=208&w=347&zc=1&q=90&a=c&s=&f=&cc=&ct=";
var parm = getParameterFromURL(url, "h");

See http://jsfiddle.net/jfriend00/86MEy/ for a working demo.

Upvotes: 0

Jason McCreary
Jason McCreary

Reputation: 73031

Regular expression to match an h url parameter containing an integer value.

[&?]h=(\d+)

The Javascript:

var match = /[&?]h=(\d+)/.exec(url_string);
alert(match[1]);

Learn more about Regular Expressions.

Upvotes: 1

Related Questions