简体   繁体   English

使用javascript和regex限制替换和捕获特定的html标签

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

I'm using javascript and regular expression to convert this html code: 我正在使用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>

into this format: 变成这种格式:

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

as you can see, what I'm trying to do is distribute the value of ==id: to all =href: within the same document tag. 如您所见,我正在尝试将== id:的值分发到同一文档标签中的所有= href:。 I'm relatively new to javascript, so any help to achieve this would be greatly appreciated. 我对javascript比较陌生,因此非常感谢您能提供帮助。

There are saner ways of doing this other than straight regex (an XML parser for example), 除了简单的正则表达式(例如XML解析器)之外,还有其他更明智的方法,
but since you asked for it ... 但是既然你要...

 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