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


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 来确定这是否直接由

最可靠的方法是解析 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;
}

您的使用案例:

→ 小提琴

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");
}

最新更新