1

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

1
  • var height = /[&?]h=(\d+)/.exec(string);height = height ? height[1] : ''; When the match is invalid, height is null, and an empty string is returned. When a match is found, match[1] holds all digits. It's a string though. If you want it to be a number, prefix it with + (or choose any other number-conversion method you like). Commented Aug 18, 2012 at 16:16

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Shouldn't it be match[1] to get only the digits?
[&?]h=(\d+) This seems to pull the &h= out as well...not just the number.any thoughts?
any harm in doing it just like this var match = string.match( /[&?]h=(\d+)/ ); alert(match[1]); ?
@Rick The code was right, except for displaying the wrong value. At index 0 you get the whole match, and that isn't what you wanted in this case. You are interested in the value and that is at index 1. See the updated code and it should be what you need.
@Rick Be aware that if there isn't a match, the variable match will be null and any reference to match[1] will result in a type error
|
0

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.

3 Comments

Why do you use parentheses at return(null); and return(matches[1]); ?
@some - it is a personal style to use parens around return values. There are some complex statements where parens are required in order to direct the JS engine to do the right thing so I am in the habit of always using them. When the return value is simple, they are not required.
@jfriend00 Ok, I understand. Automatic Semicolon Insertion is an enemy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.