获取的数据中的空格处理
获取的数据中有很多空格,加了trim()处理,还是不行,请问我的trim()哪里用错了
我的代码如下:
var http = require('http');
var cheerio = require('cheerio');
var url = 'http://www.imooc.com/learn/348';
function filterChapters(html) {
var $ = cheerio.load(html);
var chapters = $('.chapter');
var courseDate = [];
chapters.each(function (item) {
var chapter = $(this);
var chapterTitle = $(chapter.find('strong')).text().trim();
var videos = chapter.find('.video').children('li');
var chapterDate = {
chapterTitle: chapterTitle,
videos: []
}
videos.each(function (item) {
var video = $(this).find('.J-media-item');
var videoTitle = video.text().trim();
var videoID = video.attr('href').split('video/')[1];
chapterDate.videos.push({
title: videoTitle,
id: videoID
})
})
courseDate.push(chapterDate);
})
return courseDate;
}
function printDateInfo(courseDate) {
courseDate.forEach(function (item) {
var chapterTitle = item.chapterTitle;
console.log(chapterTitle + '\n');
item.videos.forEach(function (video) {
console.log(' [' + video.id + '] ' + video.title + '\n');
})
})
}
http.get(url, function (res) {
var html = '';
res.on('data', function (data) {
html += data;
})
res.on('end', function () {
var courseDate = filterChapters(html);
printDateInfo(courseDate);
})
}).on('error',function () {
console.log('获取页面数据出错');
})