How can I Strip all regular html tags except , (>

前端 未结 4 548
误落风尘
误落风尘 2020-12-21 02:29

When a user create a message there is a multibox and this multibox is connected to a design panel which lets users change fonts, color, size etc.. When the message is submit

相关标签:
4条回答
  • 2020-12-21 02:55

    Smerny's answer is working well except that the HTML structure is like:

    var s = '<div><div><a href="link">Link</a><span> Span</span><li></li></div></div>';
    var $s = $(s);
    $s.find("*").not("a,img,br").each(function() {
        $(this).replaceWith(this.innerHTML);
    });
    console.log($s.html());
    

    The live code is here: http://jsfiddle.net/btvuut55/1/

    This happens when there are more than two wrapper outside (two divs in the example above).

    Because jQuery reaches the most outside div first, and its innerHTML, which contains span has been retained.

    This answer $('#container').find('*:not(br,a,img)').contents().unwrap() fails to deal with tags with empty content.

    A working solution is simple: loop from the most inner element towards outside:

    var $elements = $s.find("*").not("a,img,br");
    for (var i = $elements.length - 1; i >= 0; i--) {
        var e = $elements[i];
        $(e).replaceWith(e.innerHTML);
    }
    

    The working copy is: http://jsfiddle.net/btvuut55/3/

    0 讨论(0)
  • 2020-12-21 02:59

    I think it would be better to extract to good tags. It is easy to match a few tags than to remove the rest of the element and all html possibilities. Try something like this, I tested it and it works fine:

    // the following regex matches the good tags with attrinutes an inner content
    var ptt = new  RegExp("<(?:img|a|br){1}.*/?>(?:(?:.|\n)*</(?:img|a|br){1}>)?", "g");
    var input = "<this string would contain the html input to clean>";              
    var result = "";
    
    var match = ptt.exec(input);                
    while (match) {
        result += match;
        match = ptt.exec(input);
    }
    
    // result will contain the clean HTML with only the good tags
    console.log(result);
    
    0 讨论(0)
  • 2020-12-21 03:07

    with jQuery you can find all the elements you don't want - then use unwrap to strip the tags

    $('#container').find('*:not(br,a,img)').contents().unwrap()
    

    FIDDLE

    0 讨论(0)
  • 2020-12-21 03:14

    Does this do what you want? http://jsfiddle.net/smerny/r7vhd/

    $("body").find("*").not("a,img,br").each(function() {
        $(this).replaceWith(this.innerHTML);
    });
    

    Basically select everything except a, img, br and replace them with their content.

    0 讨论(0)
提交回复
热议问题