JS Regex找到几个标签的href

Inf*_*ank 16 javascript regex

我需要一个正则表达式来从这些标签中找到hrefs的内容:

<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>
Run Code Online (Sandbox Code Playgroud)

只是网址,而不是href /标签.

我在这里解析一个纯文本ajax请求,所以我需要一个正则表达式.

Nie*_*els 18

你可以尝试这个正则表达式:

/href="([^\'\"]+)/g
Run Code Online (Sandbox Code Playgroud)

示例:http://regexr.com?333d1

更新:或通过非贪婪方法更容易:

/href="(.*?)"/g
Run Code Online (Sandbox Code Playgroud)


gki*_*ely 5

这样做会很好.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]);
    }
Run Code Online (Sandbox Code Playgroud)


jim*_*sun 5

这是一个强大的解决方案:

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' );
Run Code Online (Sandbox Code Playgroud)

来自 http://www.regexr.com 的彩色 href RegEx

它能做什么:

  • 检测标签
  • 懒惰跳过其他 HTML 属性和组 (1) 所以你 DRY
  • 匹配href属性
  • 考虑周围可能的空白 =
  • 做一组(2)的'",所以你DRY
  • 匹配除组 (1) 和组 (3) 之外的任何内容
  • 匹配组 (2)'"
  • 匹配组 (1)(其他属性)
  • 匹配任何其他存在直到关闭标签
  • 设置适当的标志i忽略大小写