Search code examples
javascripthtmlangularjsdommeta-tags

How to remove html DOM elements from a string (with javascript)?


Ok, so I'm building my angular application. I'm inserting about first 100 characters of the content to the "description" meta tag for facebook sharing, but there is a problem. It also adds the DOM html elements to the description. So the facebook description looks like this(sry, it's in Estonian):

"Mängu võib mängida koos alkoholiga või ilma. Mäng käib järgmiselt: <​ol> <​li>Kõikidele mängijatele antakse paber (soovitatavalt <​img class="lightbox_image" src="img/article_pictures/post_it_note.jpg" alt=""><​span class="lightbox_link" onclick="open_lightbox(this)">kleepuv post-it note<​/span>) ja…"

You can test it here: http://vivule.ee/2

I tried removing the elements before inserting them into the metatags, but I can only remove so much.

Here's an example of how I remove br tags:

  var original_description = $scope.game.description;
  original_description = original_description.replace(/<br>/g,"");

But how would I remove something like this: "<​img class="lightbox_image" src="img/article_pictures/post_it_note.jpg" alt="">", is there an easier method than regex?


Solution

  • i have no Idea about angularJS!!! but if you would use JQuery, then you could do it like this:

    create a JQuery Element from the String you have for example:

    var yourHtmlString = '<p>p contents</p> hallo <br/> <i>i contents</i>
        <img  src="img/article_pictures/post_it_note.jpg" alt="">';
    
    var div = $('<div>'+yourHtmlString+'</div>');
    

    and now, to get text only without html tags, just do:

    div.text();

    DEMO: http://jsfiddle.net/Lxyd2joa/