2012-07-16 66 views
0

我想Javascript/jquery。替换使用正则表达式通配符

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

来代替纯文本(例如)[下一个1272]文本可能出现在HTML页面的任何地方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); 

回答

0

嗯,我想过这个问题的线路,下面的作品,在情况下,它给任何人任何帮助。 虽然不是很优雅

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