Javascript 如何将部分文本分割为父标记的子项?
假设给定一个随机文本:Javascript 如何将部分文本分割为父标记的子项?,javascript,jquery,Javascript,Jquery,假设给定一个随机文本: var v=" Hi this is a text with { as opening brace and somewhere I May have another { brace and then again An { brace, but now we have a } brace then followed by another } brace and not to forget the last one } " 现在,我想为每对大括号添加一个
var v="
Hi this is a text with {
as opening brace and somewhere I
May have another {
brace and then again
An {
brace, but now we have a
}
brace then followed by another
}
brace and not to forget the last one
}
"
现在,我想为每对大括号添加一个标记,以便它定义其范围:
Hi this is a text with
<pre id=”tag1”>
{
as opening brace and somewhere I
May have another
<pre id=”tag2”>
{
brace and then again
An
<pre id=”tag3”>
{
brace, but now we have a
}
</pre>
brace then followed by another
}
</pre>
brace and not to forget the last one
}
</pre>
我的想法:
-如果遇到{
-创建元素“pre”id=0
-提取文本,直到遇到匹配的}为止
- 将此文本放入0之前标记的innerHTML中
- 对于第二个大括号{重复相同的步骤
- 作为pre0的子级追加
- 对所有打开和关闭支架重复此操作
但这是一个太复杂的过程。有什么简单的想法吗?最简单的方法是用替换法 拨弄
var str=$('#t').text();
var-res=str.substring(7,14);
newstr=str;
while(newstr.indexOf(“}”)>-1){
newstr=newstr.replace(“}”和“”);
}
var k=0;
while(newstr.indexOf(“{”)>-1){
k++;
newstr=newstr.replace(“{,”);
newstr=newstr.replace(“}”,“'>”);
}
document.getElementById(“t”).innerHTML=newstr;
嗨,这是一个以{作为开始大括号的文本,在某个地方我可能有另一个{大括号,然后又是一个{大括号,但是现在我们有一个}大括号,然后是另一个}大括号,不要忘记最后一个}
一句话,我的朋友:regex@beautifulcoder我想了想,但后来得出结论:正则表达式可能会遇到非正则语法吗?说实话,我以前尝试过这个,但没有成功。我想我在某个地方留下了一个错误。非常感谢你的帮助Prakar:)
$('#tag3').highlight(Variable)