Skip to content

Instantly share code, notes, and snippets.

@thenanosoft
Created September 8, 2021 07:52
Show Gist options
  • Save thenanosoft/f4be36ee5cc48b068da8209b18513358 to your computer and use it in GitHub Desktop.
Save thenanosoft/f4be36ee5cc48b068da8209b18513358 to your computer and use it in GitHub Desktop.
Update all ahref links old to new using jquery with regex
<!--
Title: Update all ahref links old to new using jquery with regex
Developer: Farhan Ellahi
Website: www.thenanosoft.com
Instagram: @thenanosoft
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Alter old link to new link on entire page using jquery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<ul>
<li><a href="https://nanosoft.com/images/farhan">nanosoft.com/images/farhan</a></li>
<li><a href="https://nanosoft.com/pdf">nanosoft.com/pdf</a></li>
<li><a href="https://nanosoft.com/gallery">nanosoft.com/gallery</a></li>
<li><a href="https://nanosoft.com/about">nanosoft.com/about</a></li>
</ul>
<script>
var oldText; // old link text
var updatedText; // updated link text
var reg = /(https:\/\/nanosoft.com\/)(.*)/; // regex
var updatedLink = "http://thenanosoft.com/$2" // $2: remain after .com path
$('a').each(function(i,link) { // for each loop
updatelink = link.href.replace(reg, updatedLink); // replace link with updated link
oldText = link.innerHTML; // store old link text
link.href = updatelink; // store & update new link
updatedText = link.innerHTML; // store new link text
link.innerHTML = updatedText; // store & update new link text
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment