console
////// 工具函数:HTML实体与字符互转
var entityMap = {
escape: {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
},
unescape: {
'&': "&",
''': "'",
'>': ">",
'<': "<",
'"': '"',
}
};
var entityReg = {
escape: RegExp('[' + Object.keys(entityMap.escape).join('') + ']', 'g'),
unescape: RegExp('(' + Object.keys(entityMap.unescape).join('|') + ')', 'g')
}
// 将HTML转义为实体
function escape(html) {
if (typeof html !== 'string') return ''
return html.replace(entityReg.escape, function(match) {
return entityMap.escape[match]
})
}
// 将实体转回为HTML
function unescape(str) {
if (typeof str !== 'string') return ''
return str.replace(entityReg.unescape, function(match) {
return entityMap.unescape[match]
})
}
////// 工具函数:HTML实体与字符互转 结束
const record = '<div class="news-item">(.*?)</div></div>'
const field = '<h3 class="title">(.*)</h3>'
let sourceData = `<h3 class="title">标题-不需要的1</h3><div class="news-item"><h3 class="title">标题1标题1</h3><div>新闻概览1新闻概览1</div><div>2019-05-12</div></div><div class="news-item"><h3 class="title">标题2标题2</h3><div>新闻概览2新闻概览2</div><div>2019-05-13</div></div><div class="news-item"><h3 class="title">标题3标题3</h3><div>新闻概览3新闻概览3</div><div>2019-05-14</div></div><div class="related-list"><h3 class="title">标题-不需要的2</h3></div><h3 class="title">标题-不需要的3</h3>`
document.querySelector('.preview-wrapper').innerText = sourceData
hightLight()
function hightLight() {
let regRecord = new RegExp(record, 'g')
let regField = new RegExp(field)
let str = ''
let records = sourceData.match(regRecord)
let splitedSourceList = sourceData.split(regRecord)
splitedSourceList.forEach((item, index) => {
console.log('item:', item, index)
if (index % 2 === 0) {
str = str + escape(item)
if (index !== splitedSourceList.length - 1) {
console.log(index)
let r = records[index / 2]
let results = regField.exec(r)
console.log(results)
if (results) {
let result = results[1]
let list = r.split(results[0])
list.forEach((item, index) => {
str = str + escape(item)
if (index !== list.length - 1) {
(results[0].split(results[1]) || []).forEach((item) => {
// str = str + escape(item)
if (index !== results[0].split(results[1]).length) {
str = str + '<span class="highlight-item">' + escape(result) + '</span>'
}
})
}
})
}
}
}
})
document.querySelector('.preview-wrapper').innerHTML = str
console.log(str)
}
<div class="preview-wrapper"></div>
.highlight-item{
background: yellow;
}