如果存在X个段,则删除url段

时间:2011-03-18 23:55:00

标签: javascript regex

有人可以用正则表达式帮助我做这件事。

我有一个网址:http://www.site.com/foo/bar

当用户点击链接时,它会将其附加到网址,使其看起来像这样

http://www.site.com/foo/bar/link1

现在对于棘手的部分,当点击第二个链接时,它会一直追加到这个网址

http://www.site.com/foo/bar/link1/link2

我想让link2替换link1,使其成为http://www.site.com/foo/bar/link2

我想注意,链接的唯一原因是这样添加,因为我使用此表达式从链接中删除'#'并将其替换为'/'

location.assign(location.href.replace(/\/?#/g, "/"))

没有#,浏览器不会知道替换哈希标记,但它导致我的当前设置问题。

否则链接看起来像http://www.site.com/foo/bar#link1我的设置不存在

我正在使用htaccess来替换page.php?type=foo&user=bar&page=link1 http://www.site.com/foo/bar/link1

所以,我的问题是如何使用/link1删除/link2但是如果/link1不存在则附加link2

我希望尽可能保持代码的动态,因为链接名称可能会发生变化。

编辑: 我的代码

var newHash    = "",
        shref      = "",
        content    = '#content',
        $c         = $("#content"),
        $cw        = $("#content-wrapper");

    $(".menu-link, #my-account-link").live('click', function(){
        shref = $(this).attr("href").split("/");
        //window.location.hash = shref[5];
        //location.assign(location.href.replace(/\/?#/g, "/"))
        window.location.hash = $(this).attr("href");
        //console.log(window.location.hash);
        return false;
    });

    $(window).bind('hashchange', function(){
        /*if (location.href.indexOf("#") > -1) {
            location.assign(location.href.replace(/\/?#/g, "/"));
        }*/
        //TODO:: Find # replace with / then find first (or maybe 3rd/) and replace everything until the next / with ""
        newHash = window.location.hash.substring(1);
        console.log(newHash);
        if(newHash)
        {
            $cw.find(content).fadeOut(200, function() {
                $cw.load(newHash + " #content-wrapper", function() {
                    $c.fadeIn();
                });
            });
        }
    });
    $(window).trigger('hashchange');

1 个答案:

答案 0 :(得分:0)

var newElement   = document.location.hash.replace('#', ''); // after hash
var pathElements = document.location.pathname.split('/');
var lastElement  = pathElements[pathElements.length - 1];
var endElements  = ['link1', 'link2', 'link3'];

// the final element not in list
if(endElements.indexOf(lastElement) === -1) {
  pathElements.push(newElement);
}
// replace last element
else {
  pathElements.pop();
  pathElements.push(newElement);
}

document.location.pathname = pathElements.join('/');