最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript RegEx: replace text in string between two "markers" - Stack Overflow

programmeradmin1浏览0评论

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!

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!

Share Improve this question asked Sep 6, 2011 at 11:23 enlozenloz 5,8649 gold badges38 silver badges57 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

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

You don't need a regex, just do:

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

Your input example terminates with [\img] not [/img] as your RE searches for.

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>

Here's my solution

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>" );
发布评论

评论列表(0)

  1. 暂无评论