100pwd
100pwd

Reputation: 140

JavaScript.replace(), To Remove Tag and Contents

i have a tag with some veriable content inside. i would like to be able to remove that tag and all its contents using a javascript srt.replace().

i would usually use something like jQuery('.tag-class').remove() but jQuery isn't an option in this case.

i believe a regular expression is what i am looking for but after poking around for quite some time, i am no closer than when i started.

i need to do this.

var myContent = 'bla bla bla <div class="remove-me">variable content here</div> something something';
// run some cool replace() here and get
// bla bla bla  something something

any suggestions would be great!

Upvotes: 0

Views: 3520

Answers (3)

David
David

Reputation: 302

var myContent = 'bla bla bla <div class="remove-me">variable content here</div> something something';
myContent = myContent.replace(/<div[\s\w"\=-]*class="remove-me"[\s\w"\=-]*>[\s\w]*<\/div>/g, "");
alert(myContent);

https://jsfiddle.net/umL1tswn/

Upvotes: 1

RobG
RobG

Reputation: 147403

Don't use a regular expression to modify HTML.

HTML is designed to be parsed by a parser, regular expressions are not (by themselves) good at parsing document markup. Better to insert the HTML as the innerHTML of a DIV or similar element, then use DOM methods to modify the content.

You can then inset the content of the DIV into the document as nodes, or get the innerHTML and insert that.

e.g.

function removeElementsFromMarkup(markup, selector) {
  var el = document.createElement('div');
  el.innerHTML = markup;
  var nodes = el.querySelectorAll(selector);

  for (var i=0, iLen=nodes.length; i<iLen; i++) {
    node = nodes[i]
    if (node.parentNode) {
      node.parentNode.removeChild(node);
    }
  }
  return el.innerHTML;
}


alert( removeElementsFromMarkup(
  '<div>foo<div class="remove-me">bar</div></div>', '.remove-me') // <div>foo</div>
);

The above uses querySelectorAll, but you should use whatever selection method will suit. Go for lowest common denominator (e.g. getElementsByTagName) if that will do the job.

If you show a real example of what you are trying to do, you'll get more specific (and probably more useful) answers.

Upvotes: 2

Andreas Louv
Andreas Louv

Reputation: 47099

If the senario is like this, you can simply use vanilla JavaScript DOM modification:

HTML:

<div id="abc">bla bla bla <div class="remove-me">variable content here</div> something something</div>

JavaScript:

var container = document.getElementById("abc"),
    items = container.getElementsByClassName("remove-me"),
    i = 0,
    len = items.length;

for( ; i < len; i++ ) {
    items[i].parentNode.removeChild(items[i]);
}

Or if you want to strip all HTML tags:

var container = document.getElementById("abc");

container.innerHTML = container.innerHTML.replace(/(<([^>]+)>)/ig,"");

Upvotes: 2

Related Questions