简体   繁体   中英

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. And after it gets printet into in element.

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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