从字符串中提取锚标记 href javascript/jquery

Extract anchor tag href from string javascript/jquery

我有一个要求,我需要 extract 来自 string1st href

假设我有这样一个字符串:

var LinkString="Google Link Is:<a href='www.Google.com' target='_blank' style='text-decoration:none; color:#000000;'>URL</a>";

现在我需要 find all the anchor tags 来自 stringextract the first anchor tag's href

我遵循了 中的这个示例,并尝试从字符串中找到锚标记。

但是我无法获取第一个元素的 href。

var LinkString="Google Link Is:<a href='www.Google.com' target='_blank' style='text-decoration:none; color:#000000;'>URL</a>";
    var output = LinkString.split(/(?=<a)/)[1];

我也试过 creating a DOM element 来自 output anchor tag 但无法按照 here

的过程获得准确的 href

我的要求是得到 Google.com 作为最终输出。

任何人都可以帮我获取 href 吗?

您可以创建 DOM 元素然后提取 anchor

var LinkString="Google Link Is:<a href='www.Google.com' target='_blank' style='text-decoration:none; color:#000000;'>URL</a>";
var firstAnchor = $('<div></div>').append(LinkString).find('a:first');
console.log(firstAnchor.prop('outerHTML')); //Get HTML
console.log(firstAnchor.attr('href')); //Get href attribute
console.log(firstAnchor.prop('href')); //Get href property
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

您必须使用 虚拟 html 元素 例如 div 将 html 字符串值放入其中然后您可以定位提取 href 的锚点:

var htm="Google Link Is:<a href='www.Google.com' target='_blank' style='text-decoration:none; color:#000000;'>URL</a>";
var href = $('<div>').append(htm).find('a:first').attr('href');
console.log(href)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

你可以这样做jsfiddle:

var LinkString="Google Link Is:<a href='www.Google.com' target='_blank' style='text-dec`oration:none; color:#000000;'>URL</a>";

var dom = jQuery.parseHTML("<div>" + LinkString + "</div>");
console.log(dom);
console.log($(dom).find("[href]").attr("href"));

这将搜索 dom 个具有 href 属性的元素并打印找到的第一个 href。