Heyo,
so I got a script
that turns normal anchor href's
into id hrefs
(for example: /10001-Link1
to #Link1
). Now this works fine as long as you repeat the code for every single anchor link
you want to turn into a id link
. But I want to make it less static. So that instead of repeating the code for every single anchor link
the script should get the correct word out of the current anchor href
automaticly and just replaces the word with the rest of the url and puts a #
before it.
So here is the code that works only for the first URL:
$(document).ready(function() {
$('li a').each(function(){
var oldUrl = $(this).attr("href");
var newUrl = oldUrl.replace("/10001-Link1", "#Link1");
$(this).attr("href", newUrl);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li><a href="/10001-Link1">Link 1</a></li>
<li><a href="/10002-Link2">Link 2</a></li>
<li><a href="/10003-Link3">Link 3</a></li>
<li><a href="/10004-Link4">Link 4</a></li>
<li><a href="/10005-Link5">Link 5</a></li>
</ul>
Now I alredy searched for a solution for this Problem. But the only thing I found was a line of code I couldn't really understand.
$('a[href^="http://stackoverflow.com"]')
.each(function()
{
this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/,
'http://stackoverflow.com');
});
I get the first part were every href that starts with http://stackoverflow.com is getting a .each
function. But I don't know what all the /
's and \
's by the .replace
part do and mean. Maybe this is not even the right solution for my problem at all?