2017-05-03 4 views
0

私は変数に次のHTML文字列「myhtml」があります。javascriptを使ってこの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文字列から抽出したいことは、「トマトベリーのクルミ」です。 HTMLページを更新するたびに、「チョコレートチップソーダ」のような「トマトの果実の胡瓜」の代わりに表示される言葉が異なることに注意してください。

私が探している文字列を抽出する最も速い方法は何ですか?私の現在の解決策は、 "..."の分割を使ってすべてを取得し、そのページ/ HTMLの変更はこれらの特定の3つの単語を除いて何もないので、単語 "Dont"に別の分割を使用することです。

スマートで高速なソリューションはありますか?

+0

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);
FYI、https://jsperf.comそれはちょうど示すことを行くjavascriptのメソッド –

答えて

1

あなたは代わりに正規表現を使用することができます。\w\sと一致するように、私のアップデートで

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]);

を私の解決策は、Firefox、ChromeとSafariで(サブインデックス方式よりも)高速である代わりに(.*)

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

+0

の性能を比較するための良いサイトです、upvoteカウントは誤解を招くことができます。 perfはすべてを見ます。 – Rolando

3

Inorスライディングウィンドウを使用すると、1回のパスをとるO(n)となるため、最も速い解決策になります。しかし、理論的にもすべてのO(n)は等価であり、結果として3回のパスを使用することは同様に高速です。

インデックスに大きなセグメントを使用して、精度を確保します。

関連する問題