Changing part of a URL and appending the URL based on specific characters jQuery
I need to look at a href in a page and see if a certain bit of text is in the URL, if it is i need to change it to something else, then append a location to the end.
if the link contains "ice/app?service=page&page=probrowse"
ex: http://www.google.com/ice/app?service=page&page=probrowse&cat=1&year=2011
I need to change it to "club/probrowse.htm?"
ex: http://www.google.com/club/probrowse.htm?cat=1&year=2011
I am currently running the script below whi开发者_运维百科ch takes into consideration ? and & in the URL and appending a location to the 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>
I ran into some other bumps due to the fact I am ingesting information from another site and need to make some minor URL changes.
The overall goal is to change
google.com/ice/app?service=page&page=probrowse&cat=1&year=2011
into
google.com/club/probrowse.htm?cat=1&year=2011&location=/abc/123
I belive this is what you are looking for:
<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>
<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>
精彩评论