我需要搜索<div>
简单文本系统的特定类,然后存储文本。
基本上,会有一个 div,并且在 div 内可能有一些文本,例如:
[ALERT](TEXT TO STORE HERE)
我想在 div 中搜索 ALERT 标记,然后将 () 内的任何文本存储在变量下(如果存在),如果找到,则将警报推送到控制台。
但是,虽然我可以轻松找到第一部分 [ALERT],但我无法弄清楚如何找到整个字符串或存储包含的文本。我认为它最终应该是这样的:
var alerttext = $("#result").find("[ALERT](.)")=(function()
{
return $(this).html();
}).get();
但是,这似乎还很遥远,而且肯定行不通。
编辑:html 类似于:
<div id="bbb" class=""><p id="aaa">text test text
[ALERT](TEXT TO STORE HERE)
More text down here
</p></div>
最佳答案
尝试使用 .text()
、 String.prototype.replace()
和 RegExp
/(\n.+\()|(\).+\n+\s+$)/g
替换输入字符串,直到 (
,从 )
到输入末尾,删除匹配字符串开头和结尾处的换行符、空格字符
var arr = [];
$("#bbb").text(function(i, text) {
if (text.indexOf("[ALERT]") >= 0) {
var match = text.replace(/(\n.+\()|(\).+\n+\s+$)/g, "");
arr.push(match);
console.log(arr);
};
return text
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="bbb" class="">
<p id="aaa">text test text [ALERT](TEXT TO STORE HERE) More text down here
</p>
</div>
关于javascript - 使用 JS 或 jQuery 解析自定义文本标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35662585/