【问题标题】:Replace plain-text properly using jQuery使用 jQuery 正确替换纯文本
【发布时间】:2015-05-16 23:12:24
【问题描述】:

这是替换文本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]

请看小提琴:http://jsfiddle.net/vw5b1szm/1/

谢谢。

【问题讨论】:

    标签: jquery html text replace replacewith


    【解决方案1】:

    你可以的

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

    演示:Fiddle

    由于您正在执行基于 dom 的替换,因此您不能分两步完成,即 [this][/this] 不能在 2 个不同的调用中替换,而是您需要在对 replaceText 的单个调用中替换它.你的第二个替换是使用replace 而不是replaceText

    【讨论】:

    • 太棒了!非常感谢。
    • 嗨,Arun 还有一件事是,当 [this] 这是 some text [/this] 然后它不起作用,请帮助。
    • 这是插件的问题...它不支持替换带有dom元素的文本
    • 这个插件的哪一行我们应该改变,请有任何建议。
    猜你喜欢
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 2018-07-18
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多