使用 jQuery 正确替换纯文本

Replace plain-text properly using jQuery

这是替换文本 script

我这样称呼它:

$(document).ready(function() {
$('#test-id').replaceText(/\[this\]/g,'<b>').replace(/\[\/this\]/g,'</b>');
});

应该只加粗[this] bold text [/this],下面HTML

<span id="test-id"> [this] This is some text that contains [/this] red color with bold text</span>

它应该只在这个 [this][/this] 内加粗文本,但问题是它也会使其他文本加粗而不是隐藏最后一个 [/this] 一个。

我也试过叫这个:

$('#test-id').replaceText(/\[this\]/g,'<b>');

所以请指教如何仅替换 [this] This is some text that contains [/this],而不替换其他文本并隐藏最后一个 [/this]

请参阅Fiddle:http://jsfiddle.net/vw5b1szm/1/

谢谢。

你可以

$('#test-id').replaceText(/\[(\/)?this\]/g, '<b>');

演示:Fiddle

因为你正在做基于 dom 的替换,你不能分两步完成,即 [this][/this] 不能在 2 个不同的调用中替换,你需要在对 replaceText 的一次调用中替换它。另外,您的第二个替换使用的是 replace 而不是 replaceText