简体   繁体   中英

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

I want to replace the plain text (for example) [next 1272] with

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

The text could appear anywhere in the page html, and more than once, perhaps with a different number (from 1 to 99999). I don't have control of how/where it might appear.

Along the lines of

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);   

Well I thought about it, and the following works, in case it's any help to anybody. Not very elegant though

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM