2011-09-06 46 views
3

我需要这之间的字符串文本:JavaScript的正则表达式:更换两个 “标志”

输入

<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

你并不需要一个正则表达式,只是做:

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

非常感谢您!这是我需要的:) – enloz

6

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

一个正则表达式应该做

测试的ouptut然后some text <img src='path_to_image'/> some other text

+0

非常感谢你的回答..它很好! – enloz

1

您的输入示例终止于[\img]而不是[/img]作为您的RE搜索。

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> 
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>");