Let's take a look at your url:
var url='<a href="<a href="/page-example">Page Example</a>">Page Example</a>';
First let's get rid of both occurences of "
url=url.replace(/"/g,'');
Now remove the first occurence of </a>
by feeding the exact string instead of a regular expression to the .replace
method.
url=url.replace('</a>','');
At this point your url looks like this:
<a href="<a href=/page-example>Page Example">Page Example</a>
We're getting closer. Let's remove anything in between the >
and the "
by
url=url.replace(/\>(.*)\"/,'"');
which gives us
<a href="<a href=/page-example">Page Example</a>
Almost done - finally let's get rid of "<a href=
url=url.replace('"<a href=','"');
To make the whole thing a bit more beautiful we can chain all four operations:
var url = '<a href="<a href="/page-example">Page Example</a>">Page Example</a>';
url = url.replace(/"/g, '').replace('</a>', '').replace(/\>(.*)\"/, '"').replace('"<a href=', '"');
console.log(url);
You can retrieve the href
value that seems to be the correct A element and replace the incorrect one with the correct one:
const a = document.querySelector('a[href]'); //if you have more <a> elements replace it to your need
const attr = a.getAttribute('href'); //get the value of 'href' attribute
const temp = document.createElement('template');
temp.innerHTML = attr; //create the new A element from the 'href' attribute's value
const newA = temp.content.children[0]; //retrieve the new <a> element from the template
a.parentElement.replaceChild(newA, a); //replace the incorrect <a> element with the new one
<a href="<a href="/page-example">Page Example</a>">Page Example</a>
Yes, using the string split() function like this...
S='<a href="/page-example">Page Example</a>';
var A=split('"');
document.write(A[1]);
This should display "/page-example", and you can then add it as the href to an anchor.
Within your process you can use regex to extract the url from the href string:
const string = "<a href="/page-example">Page Example</a>";
const url = string.match(/(\/)[\w-]*(?=&)/)[0];
console.log(url);