3
var content = "This is dummy <a href='#'>content</a> for my <a href='#'>Search String</a> and here is another Search String without an anchor tag",
    searchString = "Search String";

在 javascript/jquery 中使用正则表达式,如何确定内容字符串中的 FIRST searchString 是否包含在锚标记中?我只需要一个布尔值 true/false 来确定这是否直接由

4

1 回答 1

5

最可靠的方法是解析 HTML 并递归搜索第一次出现的文本。然后,检查该文本节点的父节点是否是锚点。

这是我编写的通用函数:

/**
  * Searches for the first occurence of str in any text node contained in the given DOM
  * @param {jQuery} dom A jQuery object containing your DOM nodes
  * @param {String} str The string you want to search for.
  * @returns {Object} Returns either null or the text node if str was found.
  */
function searchFirstTextOccurrence(dom, str) {
    var foundNode = null;

    dom.contents().each(function (idx, node) {
        if (node.nodeType == Node.TEXT_NODE) {
            if (node.textContent.indexOf(str) !== -1) {
                foundNode = node;
                // break out of each()
                return false;
            }
        } else if (node.nodeType == Node.ELEMENT_NODE) {
            var foundInnerNode = searchFirstTextOccurrence($(node), str);
            if (foundInnerNode) {
                foundNode = foundInnerNode;
                // break out of each()
                return false;
            }
        }
    });
    return foundNode;
}

您的用例:

→ jsFiddle

var content = "This is<div> dummy <a href='#'>content</a> for my <a href='#'>Search String</a> and</div> here is another Searchx String without an anchor tag";
var searchString = "Search String";

var dom = $("<div>" + content + "</div>");
var firstOccurence = searchFirstTextOccurrence(dom, searchString);
if ($(firstOccurence).closest("a").length > 0) {
    console.log("Yep");
} else {
    console.log("No");
}
于 2013-10-22T16:15:02.110 回答