Reputation: 25161
I am trying to do a find and replace throughout an entire page, and add some parameters to any URLs that contain some specified text. (i am speaking about hardcoded inline a href URLs)
So for example, I want to replace any instances of this:
<a href ="http://localhost/wordpress/">Link</a>
With
<a href ="http://localhost/wordpress/?demo_mobile_site">Link</a>
I tried some replace function I found, but I cant get it to work with the forward slashes in the string.
Any help on this would be appreciated. Thanks
Upvotes: 0
Views: 7848
Reputation: 12279
You don't need t replace anything just simple add onto a string.
$('a').each(function(){
var _href = $(this).attr('href');
$(this).attr('href', _href + (_href.charAt(_href.length-1) == '/' ? "? demo_mobile_site" : "/?demo_mobile_site");
});
or if you just want to replace the one href you can do something like this:
$('a[href^="http://localhost/wordpress"]').each(function(){
var _href = $(this).attr('href');
$(this).attr('href', (_href.charAt(_href.length-1) == '/' ? _href + "?demo_mobile_site" : "/?demo_mobile_site");
});
This including url's with query strings:
$('a').each(function(){
var _href = $(this).attr('href');
if ( _href.indexOf('?') >= 0 ){
$(this).attr('href', _href + "&demo_mobile_site=");
} else if ( _href.charAt(_href.length-1) == '/' ) {
$(this).attr('href', _href + "?demo_mobile_site");
} else {
$(this).attr('href', _href + "/?demo_mobile_site");
}
});
Upvotes: 2
Reputation: 11732
$('a[href="http://localhost/wordpress/"]').each(function(){
var newhref = $(this).attr('href') + '?mobile_site';
$(this).attr('href', newhref);
});
Upvotes: 0
Reputation: 9800
Check this sample I created with replace it works fine.
var value ="This is some text . http://localhost/wordpress/ Some text after ";
var source= "http://localhost/wordpress/";
var dest = "http://localhost/wordpress/?demo_mobile_site";
alert(value);
value= value.replace(source,dest);
alert(value);
Upvotes: 0
Reputation: 3902
Are these always in links? If so:
$('a[href="http://localhost/wordpress/"]').attr('href', 'http://localhost/wordpress/?demo_mobile_site');
Upvotes: 0