简体   繁体   中英

remove all tags and styling from object of arrays

I am getting an array of objects from an API:

var result = {
  [0]: {
    created_at: "2013-04",
    id: "444556663333",
    num_comments: 1,
    num_likes: 0,
    text: "<p>dfgg</p>",
    title: "title1",
    updated_at: "2013-04"
  },
  user: {
    first_name: "bob",
    id: "43633",
    last_name: "ddd"
  }
}

The text field brings in the original formatting from the site. This contains a bunch of different tags such as spans and characters such as, img, p, a, strong, em, br, &amp How do I strip all of that out of the objects EXCEPT the P tag in the text field BEFORE I pass it into an underscore template?

Thanks!

How can I make this work with my code? not understanding how the selector is working

var results = getCanvasPosts(CanvasID, {count: 75, start: ""}); //get posts from API

 $.when(results).done(function(posts){  
    var template = $("#template").html();

//Put function here?

    //merge template and data
    $("#target").html(_.template(template,{posts:posts} ));
 });

With jQuery you could do that in this way:

var text = '<p>asdasd</p><div>asddsa</div>';

var only_p = $('p', $('<div>' + text + '</div>'));

So you wrap your text with <div> and select only p from it

Try This

var whitelist = "p"; // for more tags use the multiple selector, e.g. "p, img"
$("#text *").not(whitelist).each(function() {
    var content = $(this).contents();
    $(this).replaceWith(content);
});

http://jsfiddle.net/JEnvr/3/

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