【问题标题】:Javascript / Jquery. Substitute plain text with html using regular expression with wildcardJavascript / Jquery。使用带通配符的正则表达式将纯文本替换为 html
【发布时间】:2012-07-16 11:06:21
【问题描述】:

我想将纯文本(例如)[next 1272] 替换为

<a href='page.asp?id=1272'>
<img src='next.png' alt='Next Page' title='Next Page' />
</a>

文本可以出现在页面 html 中的任何位置,并且不止一次,可能使用不同的数字(从 1 到 99999)。我无法控制它可能出现的方式/位置。

顺着

var ThisBody = $("body").html()
var regex = new RegExp("\\[  (I dont know) \\]", "g");
StrToReplaceWith = "...(the html in the example, with correct number)..."
ThisBody = ThisBody.replace(regex,StrToReplaceWith);
$("body").html(ThisBody);   

【问题讨论】:

    标签: javascript regex wildcard


    【解决方案1】:

    嗯,我想了想,下面的工作,以防它对任何人有任何帮助。 虽然不是很优雅

    regex = new RegExp(/\[next (.*?)\]/gi);
    mtch=ThisBody.match(regex)
    newBody=ThisBody
    if (mtch!=null)
      {
      if (mtch.length>0)
        {
        for (var i=0; i<mtch.length; i++)
            {
            tmp=mtch[i]                 // [next 1272]
            tmp=tmp.replace("]","")     // [next 1272
            tmp=tmp.substring(6)        // 1272
            t="<a href='page.asp?id=" + tmp + "'>"
            t+="<img src='Next.png' alt='Next Page' title='Next Page' />"
            t+="</a>"
            newBody=newBody.replace(mtch[i],t) 
            }
        }
      }
    ThisBody=newBody
    

    【讨论】:

      猜你喜欢
      • 2014-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-04
      • 2012-07-04
      相关资源
      最近更新 更多