DjH
DjH

Reputation: 1498

Javascript regex to replace ampersand in all links href on a page

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

Upvotes: 2

Views: 17037

Answers (2)

Patrick Knott
Patrick Knott

Reputation: 1827

Sometimes when replacing &, I've found that even though I replaced &, I still have amp;. There is a fix to this:

var newUrl = "@Model.UrlToRedirect".replace(/&/gi, '%').replace(/%amp;/gi, '&');

With this solution you replace & twice and it will work. In my particular problem in an MVC app, window.location.href = @Model.UrlToRedirect, the url was already partially encoded and had a query string. I tried encoding/decoding, using Uri as the C# class, escape(), everything before coming up with this solution. The problem with using my above logic is other things could blow up the query string later. One solution is to put a hidden field or input on the form like this:

<input type="hidden" value="@Model.UrlToRedirect" id="url-redirect" />

then in your javascript:

window.location.href = document.getElementById("url-redirect").value;

in this way, javascript won't take the c# string and change it.

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337570

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>

Upvotes: 9

Related Questions