2017-05-03 45 views
0

我有变量“MYHTML”下面的HTML字符串:如何从JavaScript中最有效地提取此html字符串的内容? (最高Peformance =最低毫秒)

<html><head><title>hackaday</title></head><body> 
<span background-color="#0000">Welcome to the world.</span><div>You want a little treat...tomatoes berries walnutsDont You? <a href="http://getyourtreat.com">Get Your Treat</a> You will enjoy it. Eat It. Love it.</div></body></html> 

我想从这个网站字符串中提取的“西红柿浆果核桃”。请注意,每次刷新HTML页面时,可能会出现不同的词语,而不是像“巧克力苏打水”那样的“西红柿浆果核桃”。

什么是提取我正在寻找的字符串的绝对最快的方式?我目前的解决方案是在“...”之后使用分隔符来获取所有内容,然后对单词“Dont”使用另一个分隔符,因为除了那些特定的三个单词外,页面/ html中的任何内容都不会更改。

是否有更智能/更快的解决方案?

+0

仅供参考,https://jsperf.com是一个很好的网站,比较的JavaScript方法 –

回答

1

您可以使用,而不是一个正则表达式:

var str = '<html><head><title>hackaday</title></head><body><span background-color="#0000">Welcome to the world.</span><div>You want a little treat...tomatoes berries walnutsDont You? <a href="http://getyourtreat.com">Get Your Treat</a> You will enjoy it. Eat It. Love it.</div></body></html>'; 
 
var pattern = /\.{3}([\w\s]+)Dont/; 
 
console.log(str.match(pattern)[1]);

用我的更新,以匹配\w\s,而不是(.*)我的解决办法是在Firefox,Chrome和Safari(比子指数法)快

https://jsperf.com/substring-index-vs-regex

+0

性能这只是表明,在给予好评数可能会产生误导。 perf看透了所有。 – Rolando

3

Inor y,使用滑动窗口将是最快的解决方案,因为它需要一次传递并且是O(n)。然而,理论上所有的O(n)都是相同的,因此使用3遍的结果同样快。

在您的索引中使用大段以确保准确性。

var htmlString = "<html><head><title>hackaday</title></head><body><span background-color=\"#0000\">Welcome to the world.</span><div>You want a little treat...tomatoes berries walnutsDont You? <a href=\"http://getyourtreat.com\">Get Your Treat</a> You will enjoy it. Eat It. Love it.</div></body></html>"; 
 
var start = "<div>You want a little treat..."; 
 
var end = "Dont You? <a href=\"http://getyourtreat.com"; 
 
var startIndex = htmlString.indexOf(start);//pass one 
 
var endIndex = htmlString.indexOf(end);//pass two 
 
var result = htmlString.substring(startIndex+start.length,endIndex);//pass three 
 
console.log(result);

相关问题