I want to change the href URL from the HTML string.
But it prints the old URL instead of the test.php
var html='<div><a href="https://www.spectrum.net/support/manage-account/creating-username?cid=eml_ehh_60_0621">find out how</a></div>';
$(html).find('a').each(function(){
var newUrl = "test.php";
$(this).attr("href", newUrl);
});
console.log(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
OUTPUT:
<div><a href="https://www.spectrum.net/support/manage-account/creating-username?cid=eml_ehh_60_0621">find out how</a></div>
It prints the same URL it’s not changing to the new URL test.php
EXPECTED OUTPUT:
<div><a href="test.php">find out how</a></div>
>Solution :
Use replace to change URL.
Example:
var html = '<div><a href="https://www.spectrum.net/support/manage-account/creating-username?cid=eml_ehh_60_0621">find out how</a></div>';
$(html).find('a').each(function(i, ...v) {
var Url = $(this).attr('href');
var newUrl = "test.php";
html = html.replace(Url, newUrl);
});
console.log(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>