How do I rewrite an href value, using jQuery?
I have links with a default city
<a href="/search/?what=parks&city=Paris">parks</a>
<a href="/search/?what=malls&city=Paris">malls</a>
If the user enters a value into a #city textbox I want to replace Paris with the user-entered value.
So far I have
var newCity = $("#city").val();
Given you have unique
hrefvalues (?what=parks, and?what=malls) I would suggest not writing a path into the$.attr()method; you would have to have one call to$.attr()for each uniquehref, and that would grow to be very redundant, very quickly – not to mention difficult to manage.Below I’m making one call to
$.attr()and using a function to replace only the&city=portion with the new city. The good thing about this method is that these 5 lines of code can update hundreds of links without destroying the rest of thehrefvalues on each link.One thing you may want to watch out for would be spaces, and casing. You could convert everything to lower case using the
.toLowerCase()JavaScript method, and you can replace the spaces with another call to.replace()as I’ve down below:Online Demo: http://jsbin.com/ohejez/