简体   繁体   English

Jquery正则表达式替换开始和结束标记是字符串

[英]Jquery regex replace opening and closing tags is in string

Here is my html that I am trying to locate in a string, and replace whole thing (itself and its children) with new html. 这是我的html,我试图找到一个字符串,并用新的HTML替换整个事物(本身及其子)。

I want to replace everything between and including <div id="image_insert">...</div> with (for example) "test". 我想用(例如)“test”替换<div id="image_insert">...</div>之间的所有内容。 Is this possible? 这可能吗?

I've tried: 我试过了:

content.replace('<div id="image_insert">[entire string in here]</div>', 'test');
content.replace(/<div id="image_insert">[entire string in here]</div>/g, 'test');
content.replace(/<div id="image_insert"></div>/g, 'test');

But with no effect. 但没有效果。 Any thoughts? 有什么想法吗? Not very good at regex's. 正则表达式并不是很好。

You just need to escape slash in the </div> . 你只需要在</div>转义斜杠。 And (.*) is regular expression for any possible characters. 并且(.*)是任何可能字符的正则表达式。 So this will work: 所以这将有效:

   content = content.replace(/<div id="image_insert">(.*)<\/div>/g, 'test');

Have a look: http://jsfiddle.net/J84nt/1/ 看看: http//jsfiddle.net/J84nt/1/

Are you trying to modify the DOM, or only the string? 您是在尝试修改DOM还是仅修改字符串? If your goal is to modify the DOM, then you can use jQuery's replaceWith instead of RegEx. 如果您的目标是修改DOM,那么您可以使用jQuery的replaceWith而不是RegEx。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM