Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Regex to find href of several a tags

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

<p class="bc_shirt_delete">
   <a href="/CustomContentProcess.aspx?CCID=13524&amp;OID=3936923&amp;A=Delete" onclick="javascript:return confirm('Are You sure you want to delete this item?')">delete</a>
</p>

Just the urls, not the href/ tags.

I'm parsing a plain text ajax request here, so I need a regex.

like image 293
Infra Stank Avatar asked Dec 10 '12 13:12

Infra Stank


3 Answers

You can try this regex:

/href="([^\'\"]+)/g

Example at: http://regexr.com?333d1

Update: or easier via non greedy method:

/href="(.*?)"/g
like image 117
Niels Avatar answered Nov 19 '22 12:11

Niels


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

Regex example: https://regex101.com/r/nLXheV/1

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]);
}
like image 20
gkiely Avatar answered Nov 19 '22 12:11

gkiely


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' );

Coloured href RegEx from http://www.regexr.com

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
like image 6
jimasun Avatar answered Nov 19 '22 12:11

jimasun