JavaScript RegEx:在两个“标记”之间替换字符串中的文本
Posted
技术标签:
【中文标题】JavaScript RegEx:在两个“标记”之间替换字符串中的文本【英文标题】:JavaScript RegEx: replace text in string between two "markers" 【发布时间】:2011-11-11 06:09:12 【问题描述】:我需要这个:
输入
<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
感谢您的帮助!
【问题讨论】:
【参考方案1】:一个像
这样的正则表达式var output = input.replace (/\[img\](.*?)\[\/img\]/g, "<img src='$1'/>");
应该这样做
那么你的测试输出就是some text <img src='path_to_image'/> some other text
【讨论】:
【参考方案2】:您不需要正则表达式,只需:
var output = input.replace ("[img]","<img src=\"").replace("[/img]","\">");
【讨论】:
非常感谢!这就是我需要的:)【参考方案3】:当您的 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>
【讨论】:
【参考方案4】:这是我的解决方案
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>" );
【讨论】:
以上是关于JavaScript RegEx:在两个“标记”之间替换字符串中的文本的主要内容,如果未能解决你的问题,请参考以下文章
构建正则表达式(RegEx)以提取 HTML 标记的文本 [重复]
Javascript Regex 从两个不同格式的文本块中获取特定字符串
JavaScript之正则匹配索引RegExpmatchAllreduceconcattoStringsplitincludesString/d