简体   繁体   中英

strip a div and all child elements from a string with JavaScript replace RegEx

I have a block of HTML stored in a variable called address_form , within that block of HTML I want to remove, or replace, a portion of it. The part I want to replace is a div with an ID of address_container .

There's clearly something wrong with my RegEx here that i'm using with the replace function as it is not working:

var tempStr = address_form.replace('/\\<div id=\\"#address_container\\"\\>.*<\\/div\\>/', '');

I simply want to replace a string, within a string.

Since you've tagged your question with jQuery, then I would suggest you use jQuery to do this task. Something like:

var tempStr = jQuery(address_from).remove('#address_container').html();

Don't do that, just get the contents of the div and replace the parent of that div with the contents.

So

var tempStr = $('#address_container').html(); // or text()
$('#parent_of_address_container').html(tempStr);

Your regex is wrong. Use this instead:

address_form.replace(/<div id=["-]#address_container["-]>.*<\/div>/,'');

From @RidgeRunner

Correctly matching a DIV element, (which itself may contain other DIV elements), using a single JavaScript regex is impossible. This is because the js regex engine does not support matching nested structures.

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