【问题标题】:Parse HTML file with NodeJS使用 NodeJS 解析 HTML 文件
【发布时间】:2012-09-23 07:00:49
【问题描述】:

我在 Nodejs 中以字符串形式加载了一个简短的 html 文件。

<html>
<head>
    <title>NodeJS</title>
    <link href="/style/application.css" rel="stylesheet" type="text/css">
    <script type="text/javascript" src="/scripts/script.js"></script>
    <link rel="shortcut icon" href="/favicon.ico">
  </head>
<body>
<center>
<h1><a href="#"><% title %></a></h1><br>
</center>
</body>
</html>

我需要获取&lt;%%&gt; 之间的每个字符串的数组。在这种情况下,只有标题。

尝试了一些 javascript 字符串函数和正则表达式,但找不到任何东西...

也许找到&lt;% %&gt; 的所有位置并以编程方式分割字符串?

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    真正的正则表达式可以为您解决问题:

    var str = document.getElementById('template').innerHTML,
        re = /<%\s*(.*?)\s*%>/g,
        matches,
        results = [];
    
    while((matches = re.exec(str)) !== null) {
        results.push(matches[1]);
    }
    
    console.log(results);
    

    DEMO

    【讨论】:

    • 完美无瑕。我必须更多地了解 RegEx。潜力很大
    【解决方案2】:

    如果您在相关字符串上调用.split("%"),那么只要页面上没有% 的任何实例,返回的数组中的每个奇数索引都应该包含您想要的字符串。

    另一种处理方式是首先调用string.split("&lt;%"),然后在奇数索引上调用string.split("%&gt;"),如果你碰巧有%是页面中其他使用的字符的实例。

    【讨论】:

      猜你喜欢
      • 2014-05-29
      • 2017-04-20
      • 2010-10-10
      • 2015-12-02
      • 2015-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-23
      相关资源
      最近更新 更多