如何确定搜索字符串是否由更大的字符串-javascript正则表达式中的锚标记包装

时间:2013-10-22 16:09:12

标签: javascript jquery regex

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来确定它是否由

直接包装

1 个答案:

答案 0 :(得分: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");
}