I'm using node.js to pull in html from an API, I'm storing it in a variable before I display it. I need to replace a link in that html string but I'm only able to use the front part of the link to search, as they will be dynamic.
I found an example that would work great using document.querySelectorAll("a[href^='http://somelink.com/12345678']")
Javascript getElement by href?
But I'm not using the DOM.
Dynamic Links that need to be removed/replaced:
<a href="http://somelink.com/12345678-asldkfj>Click Here</a>
<a href="http://somelink.com/12345678-clbjj>Click Here</a>
<a href="http://somelink.com/12345678-2lksjd>Click Here</a>
What I can search on:
<a href="http://somelink.com/12345678
I need to either change the actual link name "Click Here" or remove the element.
Any ideas how to achieve this with plain JS? Initially I'm thinking maybe there is a way to create a fake/temp DOM?
EDIT: Modifying the answer below with my code, it did exactly what I needed.
var str = '<a href="http://somelink.com/12345678-asldkfj">Click Here</a><a href="http://somelink.com/12345678-clbjj">Click Here</a><a href="http://somelink.com/12345678-2lksjd">Click Here</a>';
var div = document.createElement("div");
div.innerHTML = str;
var links = div.querySelectorAll("a[href^='http://somelink.com/12345678']");
for(i=0; i<links.length; i++) {
if(links[i]) {
str = str.replace(links[i].outerHTML, 'New Name');
}
}
console.log(str);