2017-08-04 24 views
0

如何遍历HTML中的所有标题,并用div在div中包含一个唯一的node.js?Node.js:用div标签包装所有标题

我不能使用正则表达式替换为div编号必须是唯一的

Cheerio似乎是网络中的node.js刮的最佳框架,但我没有看到解决这个用例

的一种方式
+0

一个简单的正则表达式就足够了,不是吗? – lumio

+0

你已经尝试过了什么?好像你要求我们为你写代码... – jakerella

+0

@lumio不,作为div id将需要是唯一的 –

回答

1

好吧,据我了解,你想用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); 
+0

伟大的答案 - 有趣的是,cheerio解决方案也为标题添加了一个ID –

+0

正则表达式版本似乎没有用div格式包裹标题 –

+0

[我在这里创建了一个CodePen](https://codepen.io/lumio/pen/jLmLJK),它使用RegEx解决方案。你是什​​么意思,cheerio解决方案也为标题添加了一个ID。它不应该那样做。至少当我测试它时。您使用的是什么NodeJS和cheerio版本? – lumio