使用NodeJSparsingHTML文件

我有一个简短的html文件作为一个string在Nodejs中加载。

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

我需要获取<%%>之间的每个string数组。 在这种情况下只有标题。

尝试了一些JavaScriptstring函数和正则expression式,但无法find任何东西…

也许find<% %>所有职位,并编程切片的string?

真正的正则expression式可以为你做的伎俩:

 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

如果对所讨论的string调用.split("%") ,那么只要在页面中没有任何%实例,返回数组中的每个奇数索引都应包含所需的string。

另一种做事的方法是首先调用string.split("<%") ,然后在奇数索引上调用string.split("%>") ,如果碰巧有%的情况在你的页面中使用的字符。