【问题标题】:JavaScript RegEx: replace text in string between two "markers"JavaScript RegEx:在两个“标记”之间替换字符串中的文本
【发布时间】: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

感谢您的帮助!

【问题讨论】:

    标签: javascript regex string replace


    【解决方案1】:

    一个像

    这样的正则表达式
    var output = input.replace (/\[img\](.*?)\[\/img\]/g, "<img src='$1'/>");
    

    应该这样做

    那么你的测试输出就是some text &lt;img src='path_to_image'/&gt; 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>" );
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-07-23
          • 2019-12-25
          • 1970-01-01
          • 1970-01-01
          • 2020-06-26
          • 1970-01-01
          相关资源
          最近更新 更多