Question

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.

Was it helpful?

Solution

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];
(...)

OTHER TIPS

You can try this:

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

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];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top