Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript RegEx: replace text in string between two "markers"

I need this:

Input

<div>some text [img]path_to_image.jpg[\img]</div>
<div>some more text</div>
<div> and some more and more text [img]path_to_image2.jpg[\img]</div>

Output

<div>some text <img src="path_to_image.jpg"></div>
<div>some more text</div>
<div>and some more and more text <img src="path_to_image2.jpg"></div>

This is my try and also fail

var input  = "some text [img]path_to_image[/img] some other text";
var output = input.replace (/(?:(?:\[img\]|\[\/img\])*)/mg, "");
alert(output)
//output: some text path_to_image some other text

Thanks for any help!

like image 212
enloz Avatar asked Aug 02 '26 14:08

enloz


1 Answers

A regexp like

var output = input.replace (/\[img\](.*?)\[\/img\]/g, "<img src='$1'/>");

should do

The ouptut of your test is then some text <img src='path_to_image'/> some other text

like image 111
Py. Avatar answered Aug 04 '26 03:08

Py.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!