用跨度包裹字符串

时间:2013-08-30 16:42:52

标签: javascript jquery regex dom

例如,我在我的contenteditable div中有一个文本,如下所示:

<div id = "board">
    <div>#include<iostream.h></div>
    <div></div>
    <div>int main(){</div>
    <div>
        clrscr
           <span id="openParen">(</span>
           <span id="closeParen">)</span>     
        ;   
    </div>
    <div>return 0;</div>
    <div>}</div>
</div>

如果我看到一些关键字,它将包含在span中。

<div id = "board">
    <div><span class="fragment">#include<iostream.h></span></div>
    <div></div>
    <div>int <span class="fragment">main</span>(){</div>
    <div>
        <span class="fragment">
        clrscr
           <span id="openParen">(</span>
           <span id="closeParen">)</span>     
        ;
        </span>   
    </div>
    <div>return 0;</div>
    <div>}</div>
</div>

我完成了#include和main等关键字的包装,但我无法使用此代码(来自https://stackoverflow.com/users/2684660/funkwurm)包装clrscr():

$('#board').children().each(function(index, child) {
   var text = $(child).html();
       text = text.replace(/(#include(\s*&lt;.*&gt;)?)/g, '<span class="frag">$1</span>');
       text = text.replace(/(main)/g, '<span class="frag">$1</span>');
       text = text.replace(/(clrscr)/gi, '<span class="frag">$1</span>');
       $(child).html(text);
});

2 个答案:

答案 0 :(得分:3)

jQuery版本(非CoffeeScript)工作jsFiddle

$('#board').children().each(function(index, child) {
    var text = $(child).html();
    text = text.replace(/(#include(\s*&lt;.*&gt;)?)/gi, '<span>$1</span>');
    text = text.replace(/(main\(.*\))/gi, '<span>$1</span>');
    $(child).html(text);
});

事实证明你不能像我在dcro的答案中建议的那样使用text()

答案 1 :(得分:1)

要匹配#include,#include,main()和main(...一些参数..),你可以通过原始div的子节点和每个行使用正则表达式进行匹配和替换:

text = child.html();
text = text.replace(/(#include(\s*&lt;.*&gt;)?)/gi, '<span>$1</span>');
text = text.replace(/(main\(.*\))/gi, '<span>$1</span>');
child.html(text);

查看JSFiddle demo。您可能需要为自己的用例调整正则表达式。