更改URL的一部分并根据特定字符jQuery附加URL

时间:2011-06-13 23:46:10

标签: jquery

我需要查看页面中的href并查看URL中是否有一些文本,如果是,我需要将其更改为其他内容,然后将位置附加到末尾。

如果链接包含“ice / app?service = page& page = probrowse”

ex:http://www.google.com/ ice / app?service = page& page = probrowse & cat = 1& year = 2011

我需要将其更改为“club / probrowse.htm?”

ex:http://www.google.com/club/probrowse.htm?cat=1&year=2011

我目前正在运行下面的脚本吗?和&在URL中并将位置附加到href。

<script type="text/javascript">
    jQuery(document).ready(function(){  
        jQuery('a').attr('href', function() {
                return (this.href.indexOf("?") >= 0) ? this.href + "&location=/abc/123" : this.href + "?location=/abc/123";
           });

    });
</script>

由于我从其他网站提取信息并需要进行一些小的网址更改,我遇到了一些其他障碍。

总体目标是改变

google.com/ice/app?service=page&page=probrowse&cat=1&year=2011

google.com/club/probrowse.htm?cat=1&year=2011&location=/abc/123

2 个答案:

答案 0 :(得分:1)

我相信这就是你要找的东西:

<script type="text/javascript">
jQuery.noConflict();
jQuery(function(){
    var substr = 'ice/app?service=page&page=probrowse';
    var newstring = 'club/probrowse.htm?';
    jQuery("a").each(function(){
        if(this.href.indexOf(substr) != -1){
            var newHref = this.href;
            newHref = newHref.replace(substr, newstring);
            newHref += '&location=/abc/123';
            newHref = newHref.replace('?&','?');
            this.href = newHref;
        }
    });
});
</script>

答案 1 :(得分:0)

<script type="text/javascript">
    jQuery.noConflict();
    jQuery(function(){
        var substr = 'ice/app?service=page&page=probrowse';
        var newstring = 'club/probrowse.htm?';
        jQuery("a").attr('href', function(){
            if(this.href.indexOf(substr) != -1){
                var newHref = this.href;
                newHref = newHref.replace(substr, newstring);
                newHref += '&location=/abc/123';
                newHref = newHref.replace('?&','?');
                this.href = newHref;
} else {
        return (this.href.indexOf("?") >= 0) ? this.href + "&location=/abc/123" : this.href + "?location=/abc/123"; 
    }

        });
    });
    </script>