簡體   English   中英

Javascript / Jquery。 使用帶通配符的正則表達式用html替換純文本

[英]Javascript / Jquery. Substitute plain text with html using regular expression with wildcard

我想將純文本(例如)[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);   

好吧,我想了一下,下面的方法可以對任何人有幫助。 雖然不是很優雅

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM