从 [wiki] 单词 [/wiki] 之间复制单词并添加到输出中



我使用我自己创建的bbcode [wiki] [/wiki],所以封装在这些代码之间的每个单词都会创建一个指向我的wiki的链接。请参阅下面的代码。这很好用。

if (show_wiki_dscn == true ){
    var wiki_start = '<a class="fancywiki" href="http://www.domain.com/support/wiki-inline/';
    var wiki_end = '" data-fancybox-type="iframe"><i class="fa fa-question-circle fa-1x"></i></a>';
    $('div.content_body').each(function() {     
        $(this).html( $(this).html().replace( /[wiki]/g, wiki_start ).replace( /[/wiki]/g, wiki_end));
    })
} else {
    var wiki_start = '<a class="pop-tooltip" href="http://www.domain.com/support/wiki/';
    var wiki_end = '" target="blank" title="Read our wiki"><i class="fa fa-question-circle fa-1x"></i></a>';
    $('div.content_body').each(function() {
        $(this).html( $(this).html().replace( /[wiki]/g, wiki_start ).replace( /[/wiki]/g, wiki_end));
    })
}   

现在我的问题。我想显示维基"单词"而不是问号。

那么我该如何复制[wiki]word[/wiki]并用"单词"替换<i class="fa fa-question-circle fa-1x"></i>

您需要使用单个正则表达式,并捕获单词:

$('div.content_body').each(function() {     
    $(this).html( $(this).html().replace( /[wiki](.*?)[/wiki]/g, '<a class="fancywiki" href="http://www.domain.com/support/wiki-inline/" data-fancybox-type="iframe">$1</a>'));
})

我在替换字符串中使用$1来插入它。

我还建议您阅读 在 Javascript 中构建 HTML 字符串真的不安全吗?关于您的替换方法,因为它目前不安全。

最新更新