Javascript regex to replace ampersand in all links href on a page
12,665
Your current code replaces the text of the element within the jQuery object, but does not update the element(s) in the DOM.
You can instead achieve what you need by providing a function to attr()
which will be executed against all elements in the matched set. Try this:
$("a").attr('href', function(i, value) {
return value.replace(/&/g, "and");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="/this-&-that">link</a>
<a href="/foo-&-bar">link</a>
Related videos on Youtube
Author by
DjH
Updated on September 16, 2022Comments
-
DjH over 1 year
I've been going through and trying to find an answer to this question that fits my need but either I'm too noob to make other use cases work, or their not specific enough for my case.
Basically I want to use javascript/jQuery to replace any and all ampersands (&) on a web page that may occur in a links href with just the word "and". I've tried a couple different versions of this with no luck
var link = $("a").attr('href'); link.replace(/&/g, "and");
Thank you
-
Tushar over 8 yearsDo you think
$('a[href*="&"]')
will be bit faster -
Rory McCrossan over 8 yearsPossibly - it would depend on how many
a
elements are in the DOM and how many of them you're expecting to have to work on. I'd be interested to see a JSPerf test comparison though. -
DjH over 8 yearsThat did it, thank you! Would you mind dumbing down this line for me? function(i, value)
-
Rory McCrossan over 8 yearsIt's a function which is executed for each element the selector matches, and returns the value to update the attribute to. The parameters are the index of the element and the current value of the named attribute. See this for more info: api.jquery.com/attr/#attr-attributeName-function