简体   繁体   English

从 JS 中的 html 页面解析自定义文本标签

[英]Parsing custom text tag from html page in JS

I have an HTML page with text tag like that:我有一个带有文本标记的 HTML 页面,如下所示:

<div id="container">
[stag id="789"]some content 1[/stag]
</div>

<span id="somespan">
[stag vn="78988" id="532"]some content 2[/stag]
</span>

[stag id="891" vn="78988"]some content 3[/stag]

I would like to parse the entire page code using js and get all the stag attribute and content and also replace them in-place with generated div.我想使用 js 解析整个页面代码并获取所有stag属性和内容,并用生成的 div 就地替换它们。

Notice: it isn't a valid tag it's square bracketed, and must be visible as plain text on page when js not loaded, and as div if parsed.注意:它不是一个有效的标签,它被方括号括起来,并且在未加载 js 时必须以纯文本形式在页面上可见,并且在解析时作为 div 可见。

getElementsByTagName won't work in that case, because [stag] is not a valid HTML tag, is the plain text of the web page. getElementsByTagName 在这种情况下不起作用,因为[stag]不是有效的 HTML 标记,是网页的纯文本。

What is the best way to accomplish that, in a way to be able to dynamically parse that tag.以一种能够动态解析该标签的方式来实现这一目标的最佳方法是什么。

I believe I'm asking for help to create: getElementsBySquereBracketsTagName我相信我是在寻求帮助来创建: getElementsBySquereBracketsTagName

Thanks allot for your kind help!感谢您的帮助!

It may not be valid markup because you will end up with DIVs in a span but here is one way to do it.它可能不是有效的标记,因为您最终会在一个跨度内得到 DIV,但这是一种方法。

Given HTML给定 HTML

<html>
    <body>
        <div id="container">
        [stag id="789"]some content 1[/stag]
        </div>

        <span id="somespan">
        [stag vn="78988" id="532"]some content 2[/stag]
        </span>

        [stag id="891" vn="78988"]some content 3[/stag]
    </body>
</html>

JavaScript JavaScript

document.body.innerHTML = 
document.body.innerHTML.replace(/\[/gi,'<').replace(/\]/gi,'>').replace(/stag/gi,'div')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM