Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split and replace href

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

like image 785
Youss Avatar asked Dec 12 '25 14:12

Youss


1 Answers

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')
});
like image 128
Denys Séguret Avatar answered Dec 14 '25 05:12

Denys Séguret