jQuery 如果字符串包含 link return link 值

jQuery if string contains a link return link value

使用正则表达式检查字符串是否有 link

<p>Random text <a href="/landing.html">click here</a></p>
<p>Another paragraph without href</p>

如果为真 return 字符串并使用 str.find("a").attr("href"); 获取 href 值。

var str = $('p').html();
if(new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?").test(str)) {
    console.log(str);
    var href = str.find("a").attr("href");
}

但是,console.logreturns错误

Uncaught TypeError: str.find is not a function

检查 Link Jsfiddle提前

以上代码的问题在于您使用的是 .html() 方法,因为 html returns html 部分不是 dom 对象。您需要使用 dom 选择器对象来查找锚点。将您的代码更新为以下

var str = $('p');
console.log(str)
if(new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?").test(str.html())) {
    console.log(str);
    var href = str.find("a").attr("href");
  console.log(href)
}

勾选 fiddle updated fiddle

改变
var href = str.find("a").attr("href");
对于
var href = $('p').find("a").attr("href");

您收到此错误是因为您试图在没有该方法的 "string" 中调用方法 "find"。

var str = $('p').html();
if(new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?").test(str)) {
 console.log(str);
 var href = $('p').find("a").attr("href");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Random text <a href="/landing.html">click here</a></p>
<p>Another paragraph without href</p>