JS Regex to find href of several a tags

后端 未结 9 1220
野性不改
野性不改 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 = /]*?)href\s*=\s*(['"])([^\2]*?)\2\1*>/i,
        link_text = 'another article link',
        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

提交回复
热议问题