簡體   English   中英

使用javascript和regex限制替換和捕獲特定的html標簽

[英]Using javascript and regex to limit replacement and capture within a specific html tag

我正在使用javascript和正則表達式轉換此html代碼:

  <html>
        <body>
              <document>
                     ==id:firstid;
                     ==href:#anchor32145;
                     ==href:#anchor31274;
                     ==href:#anchor98751;
              </document>
              <document>
                     ==id:secondid;
                     ==href:#anchor62341;
              </document>
              <document>
                     ==id:thirdid;
                     ==href:#achor52153;
                     ==href:#anchor98421;
              </document>
        </body>
  </html>

變成這種格式:

  <html>
        <body>
              <document>
                     ==id:firstid;
                     ==href: firstid #anchor32145;
                     ==href: firstid #anchor31274;
                     ==href: firstid #anchor98751;
              </document>
              <document>
                     ==id:secondid;
                     ==href: secondid #anchor62341;
              </document>
              <document>
                     ==id:thirdid;
                     ==href: thirdid #anchor52153;
                     ==href: thirdid #anchor98421;
              </document>
        </body>
  </html>

如您所見,我正在嘗試將== id:的值分發到同一文檔標簽中的所有= href:。 我對javascript比較陌生,因此非常感謝您能提供幫助。

除了簡單的正則表達式(例如XML解析器)之外,還有其他更明智的方法,
但是既然你要...

 const str = ` <html> <body> <document> ==id:firstid; ==href:#anchor32145; ==href:#anchor31274; ==href:#anchor98751; </document> <document> ==id:secondid; ==href:#anchor62341; </document> <document> ==id:thirdid; ==href:#achor52153; ==href:#anchor98421; </document> </body> </html>` const str2 = str.replace(/(?:<document>)[\\s=\\w]*:(\\w*);[a-z0-9;:#\\s=]*/g, (m, m1, m2) => m.replace(/==href:/g, (mm) => ` ${mm} ${m1} `)) console.log(str2) 

暫無
暫無

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

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