Im trying to split and replace href using a function. The code is simple and straightforward:
html
<a href="http://nu.nl">nu.nl</a>
Jquery
$(document).ready(function () {
function rep() {
href = $('a').attr('href');
url = href.split('/');
href.replace(url[2], 'cnn.com');
}
rep()
});
As you can see Im calling the function in document ready. I tried 'prop' instead of attr with no luck. What am I doing wrong? Example: JsFiddle
You don't use what replace returns. If you want to change the href in the a element, you might change
href.replace(url[2], 'cnn.com');
to
$('a').attr('href', href.replace(url[2], 'cnn.com'));
Now, supposing you may have more than one a element, I'd suggest to replace your whole code with
$('a').attr('href', function(_, href){
url = href.split('/');
return href.replace(url[2], 'cnn.com');
});
Demonstration
If you prefer, you may also avoid the splitting using a regex :
$('a').attr('href', function(_, href){
return href.replace(/\/\/[^\/]+/, '//cnn.com')
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With