如何遍歷HTML中的所有標題,並用div在div中包含一個唯一的node.js?Node.js:用div標籤包裝所有標題
我不能使用正則表達式替換爲div編號必須是唯一的
Cheerio似乎是網絡中的node.js刮的最佳框架,但我沒有看到解決這個用例
的一種方式如何遍歷HTML中的所有標題,並用div在div中包含一個唯一的node.js?Node.js:用div標籤包裝所有標題
我不能使用正則表達式替換爲div編號必須是唯一的
Cheerio似乎是網絡中的node.js刮的最佳框架,但我沒有看到解決這個用例
的一種方式好吧,據我瞭解,你想用div來包裝所有的標題(h1-h6),其中ID存儲在一個數組中(大約)。
您當然可以使用cheerio
(請參閱底部的解決方案),但我認爲使用RegEx也可以實現同樣的效果。
// I define the HTML in a simple constant for now.
// Use it for both solutions.
const html = `
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Text</title>
</head>
<body>
<div class="content">
<h1>Hello world</h1>
<p>Lorem Ipsum</p>
<h2>This is a small HTML example</h2>
</div>
</body>
</html>
`;
與正則表達式的第一個解決方案:
// Use html-constant from above!
function convertHeadlines(html) {
const r = /(<h\d>[\s\S]+?<\/h\d>)/g; // See https://regex101.com/r/jNjbXh/1 for explanation
const ids = [];
// Replace every match and wrap it with a new DIV.
const output = html.replace(r, (match) => {
const newId = `headline${ ids.length + 1 }`;
ids.push(newId);
return `<div id="${ newId }">${ match }</div>`;
});
return {
ids,
output,
};
}
const result = convertHeadlines(html);
console.log(result);
這導致一個對象,給你所有的IDS和新的HTML。
這裏與cheerio
解決方案 - 類似的方法:
// Use html-constant from above!
const cheerio = require('cheerio');
function convertHeadlinesWithCheerio(html) {
const $ = cheerio.load(html);
const headlines = $('h1, h2, h3, h4, h5, h6');
const ids = [];
headlines.each(function (i, elem) {
const newId = `headline${ ids.length + 1 }`;
ids.push(newId);
$(this).wrap(`<div id="${ newId }"></div>`);
});
return {
ids,
output: $.html(),
}
}
const result = convertHeadlinesWithCheerio(html);
console.log(result);
偉大的答案 - 有趣的是,cheerio解決方案也爲標題添加了一個ID –
正則表達式版本似乎沒有用div格式包裹標題 –
[我在這裏創建了一個CodePen](https://codepen.io/lumio/pen/jLmLJK),它使用RegEx解決方案。你是什麼意思,cheerio解決方案也爲標題添加了一個ID。它不應該那樣做。至少當我測試它時。您使用的是什麼NodeJS和cheerio版本? – lumio
一個簡單的正則表達式就足夠了,不是嗎? – lumio
你已經嘗試過了什麼?好像你要求我們爲你寫代碼... – jakerella
@lumio不,作爲div id將需要是唯一的 –