JS Regex to find href of several a tags

后端 未结 9 1147
野性不改
野性不改 2020-12-28 08:04

I need a regex to find the contents of the hrefs from these a tags :

相关标签:
9条回答
  • 2020-12-28 08:59

    Here is a robust solution:

    let href_regex = /<a([^>]*?)href\s*=\s*(['"])([^\2]*?)\2\1*>/i,
        link_text = '<a href="/another-article/">another article link</a>',
        href = link_text.replace ( href_regex , '$3' );
    

    What it does:

    • detects a tags
    • lazy skips over other HTML attributes and groups (1) so you DRY
    • matches href attribute
    • takes in consideration possible whitespace around =
    • makes a group (2) of ' and " so you DRY
    • matches anything but group (1) and groups (3) it
    • matches the group (2) of ' and "
    • matches the group (1) (other attributes)
    • matches whatever else is there until closing the tag
    • set proper flags i ignore case
    0 讨论(0)
  • 2020-12-28 09:05

    This will do it nicely. http://jsfiddle.net/grantk/cvBae/3/

    var str = '<p href="missme" class="test"><a href="/CustomContentProcess.aspx?CCID=13524&amp;OID=3936923&amp;A=Delete" onclick="">delete</a></p>'
        
        var patt = /<a href="(.*?)"/g;
        while(match=patt.exec(str)){
        	alert(match[1]);
        }

    0 讨论(0)
  • 2020-12-28 09:06

    how about spaces around = ? this code will fix it:

    var matches = str.match(/href( *)=( *)("|'*)(.*?)("|'*)( |>)/);
    console.log(matches);
    
    0 讨论(0)
提交回复
热议问题