Jquery: Strip all specific HTML tags from string

后端 未结 4 2076
攒了一身酷
攒了一身酷 2020-12-31 20:52

I have a variable that contains a string of text and html tags, such as:

var temp = \"
Some text

More texthere

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-31 21:25

    I'll follow up on @nbrooks because his answer is very close to what you want, but not quite. @nbrooks hit on the solution by noting that html() gives you the data that is wrapped in a tag. The solution therefore is to wrap your HTML in a tag. This should do the trick for you:

    var temp = "
    Some text

    More texthere

    Even more

    "; $("" + temp + "").find('span,p'). contents().unwrap().end().end().html()`

    See http://jsfiddle.net/18u5Ld9g/1/ for an example.

    As a more general function:

    function stripTags(html, tags) {
      // Tags must be given in CSS selector format
      return $("" + html + "").find(tags).
        contents().unwrap().end().end().html();
    }
    

提交回复
热议问题