[英]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. 我有一个HTML块存储在一个名为
address_form
的变量中,在该HTML块中,我想删除或替换其中的一部分。 The part I want to replace is a div with an ID of address_container
. 我要替换的部分是一个ID为
address_container
的div。
There's clearly something wrong with my RegEx here that i'm using with the replace function as it is not working: 我的RegEx显然有问题,我在使用replace函数,因为它不起作用:
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. 既然您已经用jQuery标记了您的问题,那么我建议您使用jQuery来完成此任务。 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. 不要这样做,只需获取div的内容,然后用内容替换该div的父级。
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 来自@RidgeRunner
Correctly matching a DIV element, (which itself may contain other DIV elements), using a single JavaScript regex is impossible.
使用单个JavaScript正则表达式正确匹配DIV元素(其本身可能包含其他DIV元素)是不可能的。 This is because the js regex engine does not support matching nested structures.
这是因为js正则表达式引擎不支持匹配的嵌套结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.