Search code examples
jqueryattributeshref

Edit a portion of an attribute


I need to change the href of a link so that instead of saying .com at the end, it will say .net.

$('selector').attr('href','http://example.com');

This is the code I'm using at the moment, but it just replaces the entire attribute. I only want it to change .com.

Can someone fix my code so that it works properly? I know this is very basic but I'm a beginner with jQuery.


Solution

  • You can use the attr's callback function:

    $('selector').attr('href', function(_, href) {
        return href.replace('.com', '.net');
    });