views:

57

answers:

3

Hi all,

I need to isolate an id in a string using javascript. I've managed to get to the part where I get to the id but then I want to be able to string the rest of the string so that it only leaves the id number such as this:

  var urlString = "http://mysite.co.za/wine/wine-blog/blogid/24/parentblogid/15.aspx";


    // if the blogid is found in the url string

    if (urlString.indexOf("blogid") != -1) {
        alert("blogid id found");

        // we strip the string to isolate the blogid

        url = urlString.substring(urlString.indexOf("blogid") + 7);

        //alert("url : " + url)
        blogId = url.substring(0, urlString.indexOf("/"));

        alert("blogId : " + blogId)
    }

I need to be able to strip everything after the 24.

Thanks all.

+2  A: 
var tempString = urlString.Split("blogid")[1];
var blogIdStr = tempString.Split("/")[1];

for the integer:

var blogId = parseInt(blogIdStr);

[edit:]
long form would be:

var tempArray = urlString.Split("blogid");
// try:
// alert(tempArray, tempArray.length);
var tempString = tempArray[1];
(...)
Martin
You gotta be kidding me! :)Thanks Martin!
Sixfoot Studio
Can you tell me how the [1] works please Martin?
Sixfoot Studio
edited my answer for better understanding. ^^@other answers: I agree on the power of regexp, though for regexp-inexperienced programmers (like me), the above is far more readable and can directly be traced.Also, when debugging you'll see that the string "blogid" appears twice, thus creating a tempArray with 3 fields. Talk about greedy or not searches.
Martin
you should always use parseInt(x, 10) if you expect the number to be decimal, otherwise you could end up in hex/oct.
Andrew Bullock
Thanks Martin, I will keep that one for another rainy day! Awesome!
Sixfoot Studio
A: 

You can try this:

var blogIdStr = urlString.replace(/(.*\/blogid\/\d+).*/, "$1") 
Mic
A: 

This is one of those rare cases where a regexp is both simpler and easier to understand:

var matches = urlString.match(/\/blogid\/(\d+)\//);
if (matches) {
    var id = matches[1];
}

or, if you're not worried about errors:

var id = urlString.match(/\/blogid\/(\d+)\//)[1];
slebetman