Home > Enterprise >  Replace certain character inside multiple/all instances of an href attribute with javasacript?
Replace certain character inside multiple/all instances of an href attribute with javasacript?

Time:05-16

I'm trying to change the character "å" into "aa" inside the href attribute of a bunch of links.

Example of what i have now:

<a id="edittoaa" href="/på-landet">På landet</a>
<a id="edittoaa" href="/i-marken">I marken</a>
<a id="edittoaa" href="/på-sandet">På sandet</a>
<a id="edittoaa" href="/på-taget">På taget</a>

Example of how i want it to look after js has done it's magic:

<a id="edittoaa" href="/paa-landet">På landet</a>
<a id="edittoaa" href="/i-marken">I marken</a>
<a id="edittoaa" href="/paa-sandet">På sandet</a>
<a id="edittoaa" href="/paa-taget">På taget</a>

Basically all instances of "å" have been changed into "aa" inside the href attribute.

I tried some different code while tampering about in jsfiddle, but i can't seem to crack it. Only time i came "close" was by doing this, but besides doing what's intended, it changes all the hrefs containing an "å" to the same destination ("/paa-landet"):

var url = $('.mylink').attr('href')
url = url.replace('å', 'aa')
$('.mylink').attr('href', url)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a  href="/på-landet">Test</a>
<a  href="/på-søen">Test</a>
<a  href="/på-landet">Test</a>

CodePudding user response:

By calling $('.mylink').attr('href', url) you are setting all .myLink references. You can loop and set each of them separately.

$('.mylink').each((i, obj) => {
  var url = $(obj).attr('href');
  url = url.replace('å', 'aa');
  $(obj).attr('href', url);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a  href="/på-landet">Test</a>
<a  href="/på-søen">Test</a>
<a  href="/på-landet">Test</a>

CodePudding user response:

Well done. You only need to treat each of the links in the class separately. Have look on https://api.jquery.com/each/

  • Related