JavaScript RegEx: заменить текст в строке между двумя "маркерами" - PullRequest
3 голосов
/ 06 сентября 2011

Мне нужно это:

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>

выход

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

6 голосов
/ 06 сентября 2011

регулярное выражение типа

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

должен сделать

Выход вашего теста будет some text <img src='path_to_image'/> some other text

4 голосов
/ 06 сентября 2011

Вам не нужно регулярное выражение, просто сделайте:

var output = input.replace ("[img]","<img src=\"").replace("[/img]","\">");
1 голос
/ 06 сентября 2011

Ваш пример ввода заканчивается на [\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 голосов
/ 14 октября 2015

Вот мое решение

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>" );
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...