klye_g
klye_g

Reputation: 1242

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.

I want to replace everything between and including <div id="image_insert">...</div> with (for example) "test". 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.

Upvotes: 0

Views: 3100

Answers (2)

Ivan Chernykh
Ivan Chernykh

Reputation: 42176

You just need to escape slash in the </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/

Upvotes: 2

Nameless One
Nameless One

Reputation: 1646

Are you trying to modify the DOM, or only the string? If your goal is to modify the DOM, then you can use jQuery's replaceWith instead of RegEx.

Upvotes: 0

Related Questions