Search code examples
jqueryajaxpathname

jquery pathname and syntax


In order to load a page with ajax I have the following in my script file:

$(".ajaxed").live("click", function(event) {
    var post_slug = $(this)[0].pathname.substring(1);
    alert(post_slug);
    $.address.crawlable(true).value(post_slug);
    $("#board").load("ajax/",{slug:post_slug});
    return false;
});

When the user clicks on an anchor linking to http://www.website.com/link1 the post_slug alert is link1. But when I use this in IE8 the post_slug alert is ink1 instead of link1. What am I doing wrong ?

I guess it's .substring(1) but what can I do?


Solution

  • You can use this:

    $(this)[0].pathname.replace("/", "");
    

    Tested on IE7, Chrome: http://jsfiddle.net/mrchief/vB2Fu/3/

    You can make the replace bit more careful by using regex to replace only the starting slash

    $(this)[0].pathname.replace(/^\//, "");
    

    Update:

    For nested slugs, I changed it a bit:

    $(this)[0].pathname.substring($(this)[0].pathname.lastIndexOf("/")).replace(/^\//, "");
    

    Demo (tested on IE7, Chrome): http://jsfiddle.net/mrchief/vB2Fu/5/