2017-06-10 27 views
0

我是JS的新手。我正在用X光掃描一個網址。當刮預期標籤被刪除,但我想<br>標籤的東西,如;制動標籤在X光片上被移除

例如更換: 如果我湊像'span#scraped-portion'

<span id="scraped-portion"><span class="bold>NodeJS</span><br> 
    <span class="bold>Version:</span> 8<br><span class="bold>Date released:</span> 2017 Jan<br><span class="bold>Description:</span>Some other text 
</span> 

我會導致類似以下

NodeJS /n Version: 8Date released: 2017 JanDescription: Some other text 

的文字環繞<br>標記獲取加在一起,它會得到很難理解什麼是什麼。 所以我想<br>標籤被替換爲;之類的東西。

是否有可能或者我應該更好地使用其他庫?

+0

也許[過濾器](https://github.com/matthewmueller/x-ray#過濾器)? –

回答

0

UPDATE

我發現,而不需要利用X射線(見下文原始溶液)之前替換HTML <br>標籤的純基於X射線的溶液。

通過這種方式,您將使用X-Ray的filter函數以及嵌入X射線功能(嵌套類型)。

首先,我們將使用爲X-Ray定義的自定義過濾器函數(稱爲replaceLineBreak)替換原始html中的<br>標記。 其次,我們將使用替換的結果重建原始html結構(通過重新添加<span id="scraped-portion">)作爲X-Ray調用的第一個參數。

希望你會喜歡它!

var x = Xray({ 
    filters: { 
     replaceLineBreak: function (value) { return value.replace(/\<br\>/g, ';'); }, 
    } 
}); 
var html = 
` 
    <span id="scraped-portion"><span class="bold">NodeJS</span><br> 
     <span class="bold">Version:</span> 8<br><span class="bold">Date released:</span> 2017 Jan<br><span class="bold">Description:</span>Some other text 
    </span> 
`; 

x(html, 
    '#[email protected] | replaceLineBreak' /// Filter function called to replace '<br>' to ';' 
)(function (err, obj) { 
    x(`<span id="scraped-portion">${obj}</span>`, /// Restore oroginal html structure to have the outer span with id 'scraped-portion 
     '#scraped-portion' 
    )(function (err2, obj2) { res.header("Content-Type", "text/html; charset=utf-8"); res.write(obj2); res.end(); }) 
    }); 

產生的以下字符串:

NodeJS; Version: 8;Date released: 2017 Jan;Description:Some other text 

原液

爲什麼不通過X射線處理的HTML代碼之前更換的<br>標籤所有出現?

function tst(req, res) { 
var x = Xray(); 
var html = 
` 
    <span id="scraped-portion"><span class="bold">NodeJS</span><br> 
     <span class="bold">Version:</span> 8<br><span class="bold">Date released:</span> 2017 Jan<br><span class="bold">Description:</span>Some other text 
    </span> 
`.replace(/\<br\>/g, ';'); 

x 
    (
    html, 
    ['span#scraped-portion'] 
    )(function (err, obj) { res.header("Content-Type", "text/html; charset=utf-8"); res.write(JSON.stringify(obj, null, 4)); res.end(); }) 
    ; 
} 

那麼你的代碼會導致這樣的事情

NodeJS;\n Version: 8;Date released: 2017 Jan;Description:Some other text\n

這幾乎似乎滿足您的要求

+0

非常感謝,我會盡快進行測試。現在我還有一個問題。如何創建'[{「版本」:「8」,「發佈日期」:「2017年1月」,「說明」:「其他文本」}]]。我也很快爲此創建一個新問題 – Dilshod