Replace part of URL in anchor using JavaScript
Replace part of URL in anchor using JavaScript
I have the following anchor link on my page:
<a href="https://example.com/sizeguide/brand.html" id="size-guide" target="_blank"><span class="pull-right">View Size Guide</span></a>
However, I need to change the brand part of the URL for different brands using JavaScript, using a handlebars function called product.brand.domain
.
product.brand.domain
I've given the anchor a unique ID, but I can't find a way to accomplish what I need.
2 Answers
2
Use:
document.getElementById('size-guide').src='newUrl';
Suppose if you want to change brand.html to newbrand.html, then do following
var href = document.getElementById("size-guide").getAttribute('href');
href = href.replace(/(.*)/.*(.html$)/i, '$1/newbrand$2');
document.getElementById("size-guide").setAttribute("href", href);
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
you're using a template engine ? post your code here !
– Springer F
Apr 3 '18 at 13:07