将html标记替换为另一个标记,然后删除其他标记

时间:2014-02-26 12:27:14

标签: javascript jquery replace

我有textarea用户可以编辑某些文本,允许他们使用html(我知道所有用户并信任他们)然后将该textarea的内容保存在数据库中。在它变成元素之后。

如何使用<h1><h2><h3>标记替换所有标题<b>等,然后删除与<b><p>不同的所有标记

用户输入存储在如下变量中:

column_content = $('.dialog_editor').val();

2 个答案:

答案 0 :(得分:4)

尝试

$('.dialog_editor').change(function () {
    var column_content = $('.dialog_editor').val();

    var $temp = $('<div />',{html: column_content});

    //process headers
    $temp.find(':header').wrapInner('<b />').contents().unwrap();

    $temp.find('*:not(p, b)').contents().unwrap();

    $('#html').html($temp.html());
    $('#text').text($temp.html());
});

演示:Fiddle

答案 1 :(得分:2)

这应该让你开始:

var column_content =
    '<h1>Test 1</h1>\n' +
    '<p>Lorem Ipsum</p>\n' +
    '<h2>Test 2</h2>\n' +
    '<input type="button" onclick="alert(&quot;missed me&quot;)" value="Click">\n' +
    '<a href="javascript://">keep this</a>\n' +
    '<h3>Test 3</h3>\n' +
    'unwrapped text';

var $temp = $("<div></div>").html(column_content);

$temp.find("h1, h2, h3").each(function () {
    $(this).wrapInner("<b></b>").children().insertAfter(this);
});
$temp.find(":not(b, p)").each(function () {
    $(this).contents().insertAfter(this);
    $(this).remove();
});
console.log($temp.html());
/*
<b>Test 1</b>
<p>Lorem Ipsum</p>
<b>Test 2</b>

keep this
<b>Test 3</b>
unwrapped text
*/
相关问题