Javascript 用HTML元素替换文本标记

Javascript 用HTML元素替换文本标记,javascript,jquery,html,replace,token,Javascript,Jquery,Html,Replace,Token,查看像DIV这样的HTML元素并用HTML元素替换特定文本段的最佳方法是什么。例如,假设我们有标记[b]和[/b]。我想分别用和替换它们 下面的例子是我最接近实际的例子 HTML至teplace: <div id="response">This is some [b]GREAT[/b] stuff!</div> 例1: $('#response').html(function() { return $(this).text().replace('[b]', '&

查看像DIV这样的HTML元素并用HTML元素替换特定文本段的最佳方法是什么。例如,假设我们有标记[b]和[/b]。我想分别用和替换它们

下面的例子是我最接近实际的例子

HTML至teplace:

<div id="response">This is some [b]GREAT[/b] stuff!</div>
例1:

$('#response').html(function() {
    return $(this).text().replace('[b]', '<b>');
});
$('#response').html(function () {
    return $(this).text().replace('[/b]', '</b>');
});
结果1:

这是一些很棒的东西

例2:

$('#response').html(function() {
    return $(this).text().replace('[b]', $('<b>'));
});
$('#response').html(function () {
    return $(this).text().replace('[/b]', $('</b>'));
});
结果2:

这是一些很棒的东西

预期结果:

这是一些很棒的东西


两者都不起作用。前者只是将令牌替换为零,而后者将其替换为浏览器中的对象,但不是所需的HTML元素。

您的第一次尝试看起来更好,但您可能应该在一次调用中完成,以免在调用之间产生中断的HTML,例如

$('#response').html(function() {
    return $(this).text().replace('[b]', '<b>').replace('[/b]', '</b>');
});

使用正则表达式应该可以很好地:

$('#response').html(function() {
    return $(this).text().replace(/\[(\/?\w+)\]/g, "<$1>");
});
为了让这成为jQuery的答案,以下是如何将所有这些转化为一个奇特的jQuery插件以供重用:

$.fn.extend({
    unphpbb: (function () {
        var map = {
               b: "strong",
               i: "em",
               p: "p"
            },
            tokens = /\[(\/?)(\w+)\]/g,
            replacement = function ($0, $1, $2) {
                return map.hasOwnProperty($2) ? "<" + $1 + map[$2] + ">" : $0;
            },
            replaceTokens = function (i, html) {
                return html.replace(tokens, replacement);
            };

        return function () {
            return this.html(replaceTokens);
        };
    })()
});

当然,解决这个问题的首选方法是在服务器上使用bbcode解析器,并向客户端发送正确清理的HTML。在具有上述功能的客户端上执行此操作在各方面都是低劣的。

您正在寻找解析本质上是什么。Patrick Gillespie这似乎很容易实现

var result = XBBCODE.process({
    text: "Some bbcode to process here",
    removeMisalignedTags: false,
    addInLineBreaks: false
});
console.log("Errors: " + result.error);
console.dir(result.errorQueue);
console.log(result.html);// the HTML form of your BBCode

你想要一个明确的jQuery答案,还是一个纯javascript答案?这很好,但是如果OP只需要一组严格的标签来解析,并且其中一些标签有不同的输出,比如在PHPBB中[*]->,[list]->等等-您更愿意使用回调函数并检查对象的键,以检查它是否是有效的标记并获得正确的标记替换。这两个问题在我的扩展答案中都有可能出现。@Ginden最好避免:浏览器不会注意替换HTML中的内联JavaScript,但它们确实从远程URL加载脚本。@我相信jQuery的.html会评估脚本标记,与vanilla.innerHTML不同,这个漏洞在Tomalak的更新答案中得到了修复。
$('#response').html(function () {
    var map = {
        b: "strong",
        i: "em",
        p: "p"
    };
    return $(this).text().replace(/\[(\/?)(\w+)\]/g, function ($0, $1, $2) {
        if (map.hasOwnProperty($2)) {
            return "<" + $1 + map[$2] + ">";
        } else {
            return $0;
        }
    });
});
$.fn.extend({
    unphpbb: (function () {
        var map = {
               b: "strong",
               i: "em",
               p: "p"
            },
            tokens = /\[(\/?)(\w+)\]/g,
            replacement = function ($0, $1, $2) {
                return map.hasOwnProperty($2) ? "<" + $1 + map[$2] + ">" : $0;
            },
            replaceTokens = function (i, html) {
                return html.replace(tokens, replacement);
            };

        return function () {
            return this.html(replaceTokens);
        };
    })()
});
$("#response").unphpbb();
var result = XBBCODE.process({
    text: "Some bbcode to process here",
    removeMisalignedTags: false,
    addInLineBreaks: false
});
console.log("Errors: " + result.error);
console.dir(result.errorQueue);
console.log(result.html);// the HTML form of your BBCode