JavaScript RegEx:在两个“标记”之间替换字符串中的文本

时间:2011-09-06 11:23:37

标签: javascript regex string replace

我需要这个:

输入

<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>

输出

<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>

这是我的尝试,也失败了

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

感谢您的帮助!

4 个答案:

答案 0 :(得分:6)

regexp_like

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

应该

然后,您的测试结果为some text <img src='path_to_image'/> some other text

答案 1 :(得分:4)

您不需要正则表达式,只需执行:

var output = input.replace ("[img]","<img src=\"").replace("[/img]","\">");

答案 2 :(得分:1)

您的输入示例会在您的RE搜索时以[\img]而不是[/img]终止。

var input  = '<div>some text [img]path_to_image.jpg[\img]</div>\r\n'
    input += '<div>some more text</div>\r\n'
    input += '<div> and some more and more text [img]path_to_image2.jpg[\img]</div>'

var output = input.replace(/(\[img\](.*)\[\\img\])/igm, "<img src=\"$2\">");
alert(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>

答案 3 :(得分:0)

这是我的解决方案

var _str = "replace 'something' between two markers" ;
// Let both left and right markers be the quote char.
// This reg expr splits the query string into three atoms
// which will be re-arranged as desired into the input string
document.write( "INPUT : " + _str + "<br>" );
_str = _str.replace( /(\')(.*?)(\')/gi, "($1)*some string*($3)" );
document.write( "OUTPUT : " + _str + "<br>" );