如何将一些文本的片段分割为父标签的子元素?

时间:2015-01-25 13:14:40

标签: 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
}  
    "

现在我要找的是为每对大括号添加一个标签,以便定义其范围:

 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>  

为什么我要实现这个目标?

我想获得一对‘{ }’中定义的变量范围。一旦我知道了范围,我就可以在其封闭标签内点击一下该变量。

 $('#tag3').highlight(Variable)

我的想法:

- 如果遇到{

-create element“pre”id = 0

- 提取文本,直到遇到匹配}说文字

  • 将此文本放在pre 0标签

  • 的innerHTML中
  • 对于第二个支撑{重复相同步骤,

  • 追加为pre0

  • 的孩子
  • 重复所有开合括号。

但这种程序过于复杂。有什么简单的想法吗?

1 个答案:

答案 0 :(得分:2)

最简单的方法是使用替换方法

小提琴http://jsfiddle.net/PrakharThakur/a9bk08c4/

&#13;
&#13;
var str = $('#t').text();
var res = str.substring(7, 14);
newstr = str;
while (newstr.indexOf("}") > -1) {
    newstr = newstr.replace("}","</pre>");
}
var k = 0;
while (newstr.indexOf("{") > -1) {
    k++;
    newstr = newstr.replace("{","<pre id='"+k+"'>");
    newstr = newstr.replace("}","'>");
}

document.getElementById("t").innerHTML = newstr;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="t">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 }</div>
&#13;
&#13;
&#13;

使用检查工具查看效果