将特定文本替换为 class 的替换函数

Replace function that will replace specific Text to a class

您好,我正在尝试编写 jQuery replace 函数,该函数将替换 HTML 中的特定文本以生成 class.

我找到了 jQuery 和 Html。看到这个 fiddle:http://jsfiddle.net/davidThomas/juTtG/20

它用 <b>hello world!</b>

替换括号内的文本字符

很好,但我正在尝试替换更多不同的文本,如下所示:

我修改了jQuery:

// this
var content = $("body").text().replace(/(\[this\])([\s\S]*)(\[\/this\])/gi,'<b></b>');
console.log(content);
$("body").html(content);

// another
var content = $("body").text().replace(/(\[another\])([\s\S]*)(\[\/another\])/gi,'<b></b>');
console.log(content);
$("body").html(content);

// more
var content = $("body").text().replace(/(\[more\])([\s\S]*)(\[\/more\])/gi,'<b></b>');
console.log(content);
$("body").html(content);

修改后HTML:

[this]hello world 1![/this] [another]hello world 2![/another] [more]hello world more![/more]

查看修改后的问题:http://jsfiddle.net/juTtG/384

问题是它替换了 <b></b> 中的一个文本字符 我正在尝试替换更多不同的文本。 如何使修改后的 jQuery 和 HTML 起作用。

另一个问题是,是否可以用这个代替:

<div class="body"> Add a [newclass] </div>

收件人:

<div class="body">Add a <b class="newclass"></b> </div>

我希望有人能给我一些尝试的建议。

提前致谢。

根据您的“已修改 HTML”问题,请参阅 this updated fiddle

这是修改后的脚本:

$(document).ready(function() {    
    var content = $("body")
        .text()
        .replace(/(\[[\s\S]*?\])/gi, '<b>')
        .replace(/\[\/[\s\S]*?\]/gi, '</b>');
    $("body").html(content);
});

变成这样:

[this]hello world 1![/this] [another]hello world 2![/another] [more]hello world more![/more]

进入这个:

  <b>hello world 1!<b> <b>hello world 2!<b> <b>hello world more!<b>

为此:

<div class="body"> Add a [newclass] </div>

this fiddle

使用这个脚本:

$(document).ready(function() {    
    var content = $("body")
        .text()
        .replace(/\[([\s\S]*?)\]/ig, '<b class=""></b>');
    $("body").html(content);
});

让它变成这样:

<div class="body">Add a <b class="newclass"></b> </div>

HTH,

-泰德