正则表达式不会将'{'替换为'<span> {</span>'

时间:2013-07-28 12:07:50

标签: regex dom

HTML

<div id = "board_code_dup">
    <div>{abc</div>
    <div>def</div>
   div>ghi}</div>
</div>

JS

var $board_code_dup = $('#board_code_dup');
board_code_dup_html = $board_code_dup.html();

$board_code_dup.html( board_code_dup_html.replace(/{/g, "<span>{</span>") );
$board_code_dup.html( board_code_dup_html.replace(/}/g, "<span>}</span>") );

}的所有实例都已<span> } </span>正确替换,{

我的代码有什么问题?

2 个答案:

答案 0 :(得分:1)

“{”开始重复,如“{1,3}”并保留,所以你应该逃避它。

$board_code_dup.html( board_code_dup_html.replace(/\{/g, "<span>{</span>") );

答案 1 :(得分:0)

此代码有效:

var $board_code_dup = $('#board_code_dup');
board_code_dup_html = $board_code_dup.html();

$board_code_dup.html( board_code_dup_html.replace(/\{/g, "<span>{</span>").replace(/}/g, "<span>}</span>") );