gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:52:36 24 4
gpt4 key购买 nike

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 中使用正则表达式,如何确定内容字符串中的第一个 searchString 是否包含在 anchor 标记中?我只需要一个 bool 值 true/false 来确定这是否直接被

包裹

最佳答案

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

这是我写的一个通用函数:

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

关于javascript - 如何确定搜索字符串是否被较大字符串中的 anchor 标记包裹 - javascript正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19522998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com