2011-09-06 3 views
3

사이에 문자열의 텍스트를 바꿉니다자바 스크립트 정규식 : 두 개의 "마커"이 필요

입력

<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]이 아니고로 끝납니다. 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>"); 
관련 문제