我在变量“myhtml”中有以下 HTML 字符串:
<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 字符串中提取的是“tomatoes berrys walnuts”。请注意,每次刷新 HTML 页面时,可能会显示不同的单词,而不是像“巧克力片苏打水”那样的“西红柿、浆果、核桃”。
提取我正在寻找的字符串的绝对最快方法是什么?我当前的解决方案是对“...”使用拆分来获取之后的所有内容,然后对“Dont”一词使用另一个拆分,因为除了这三个特定的单词之外,该页面/html 上没有任何内容发生变化。
有更智能/更快的解决方案吗?
最佳答案
理论上,使用滑动窗口将是最快的解决方案,因为它只需要一次传递,并且时间复杂度为 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);
关于javascript - 如何使用 javascript 最有效地从该 html 字符串中提取内容? (最高性能 = 最低毫秒),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43769747/