2015-07-21 65 views
2

比方說,我有以下幾點:Cheerio:從HTML中提取文本有隔板

$ = cheerio.load('<html><body><ul><li>One</li><li>Two</li></body></html>'); 

var t = $('html').find('*').contents().filter(function() { 
    return this.type === 'text'; 
}).text(); 

我得到:

OneTwo 

相反的:

One Two 

這是同樣的結果,我得到如果我做$('html').text()。所以基本上我需要的是注入一個分離器像(空間)或\n

注意:這不是一個jQuery前端的問題更像是Cheerio和HTML解析後端的NodeJS相關的問題。

回答

4

這似乎這樣的伎倆:

var t = $('html *').contents().map(function() { 
    return (this.type === 'text') ? $(this).text() : ''; 
}).get().join(' '); 

console.log(t); 

結果:

One Two 

只是提高了自己的解決方案一點點:

var t = $('html *').contents().map(function() { 
    return (this.type === 'text') ? $(this).text()+' ' : ''; 
}).get().join(''); 
3

可以使用TextVersionJS包生成html字符串的純文本版本。您也可以在瀏覽器和node.js中使用它。

var createTextVersion = require("textversionjs"); 

var yourHtml = "<h1>Your HTML</h1><ul><li>goes</li><li>here.</li></ul>"; 

var textVersion = createTextVersion(yourHtml); 

npm下載它並且需要它與Browserify例如。

+0

項目被放棄 – Toolkit