使用 JS 或 jQuery 解析自定义文本标记

Parsing custom text tags using JS or jQuery

本文关键字:自定义 文本 JS jQuery 使用      更新时间:2023-09-26

我需要搜索特定类的<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>