user1119200
user1119200

Reputation: 61

Replacing a substring in href-attribute using jQuery

I have some "a" tags in div. I have to change part of the href. For example: http://jsfiddle.net/A6z88/, I have to change only 'foo' in the href with 'asd'. Thanks a lot and sorry for my english :D

Upvotes: 2

Views: 1623

Answers (4)

Harmen
Harmen

Reputation: 22438

The most elegant way with the fewest function calls is:

$('a').attr('href', function(i, val){
  return val.replace('foo', 'asd');
});

Upvotes: 0

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76870

I'd do

$('#links a').each(function(){
   this.href = this.href.replace('/foo/', '/asd/'); 
});

Upvotes: 2

Kangkan
Kangkan

Reputation: 15571

See: http://jsfiddle.net/A6z88/3/

Upvotes: 0

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26699

$('div a').each(function(){
   $(this).attr('href', $(this).attr('href').replace('foo', 'asd'));
});

Upvotes: 4

Related Questions