correct a bad generated link using Javascript

前端 未结 4 1504
灰色年华
灰色年华 2021-01-26 12:36

I have a system that dynamically generates links. but the html links are displayed like this :



        
相关标签:
4条回答
  • 2021-01-26 12:58

    Let's take a look at your url:

    var url='<a href="<a href=&quot;/page-example&quot;>Page Example</a>">Page Example</a>';
    

    First let's get rid of both occurences of &quot;

    url=url.replace(/&quot;/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=&quot;/page-example&quot;>Page Example</a>">Page Example</a>';
    url = url.replace(/&quot;/g, '').replace('</a>', '').replace(/\>(.*)\"/, '"').replace('"<a href=', '"');
    console.log(url);

    0 讨论(0)
  • 2021-01-26 13:00

    You can retrieve the hrefvalue 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=&quot;/page-example&quot;>Page Example</a>">Page Example</a>

    0 讨论(0)
  • 2021-01-26 13:14

    Yes, using the string split() function like this...

    S='<a href=&quot;/page-example&quot;>Page Example</a>';
    
    var A=split('&quot;');
    
    document.write(A[1]);
    

    This should display "/page-example", and you can then add it as the href to an anchor.

    0 讨论(0)
  • 2021-01-26 13:15

    Within your process you can use regex to extract the url from the href string:

    const string = "<a href=&quot;/page-example&quot;>Page Example</a>";
    const url = string.match(/(\/)[\w-]*(?=&)/)[0];
    console.log(url);

    0 讨论(0)
提交回复
热议问题