简体   繁体   English

将HTML标签替换为另一个标签,然后删除其他标签

[英]Replace html tag with another tag and then remove other tags

I have a textarea where the user can edit some text, they are allowed to use html (I know all the users and trust them) Then the content of that textarea gets saved in a database. 我有一个textarea ,用户可以在其中编辑一些文本,允许他们使用html(我知道所有用户并信任他们),然后将该textarea的内容保存在数据库中。 And after it gets printet into in element. 然后将printet放入元素中。

How do i replace all headings <h1><h2><h3> etc.. with <b> tags and then remove all tags that are different from <b> and <p> 如何使用<b>标签替换所有标题<h1><h2><h3>等,然后删除与<b><p>不同的所有标签

The user input gets stored in a variable like this: 用户输入将存储在这样的变量中:

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

Try 尝试

$('.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());
});

Demo: Fiddle 演示: 小提琴

This should get you started: 这应该使您开始:

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
*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM