console
var entityMap = {
escape: {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
},
unescape: {
'&': "&",
''': "'",
'>': ">",
'<': "<",
'"': '"',
}
};
var entityReg = {
escape: RegExp('[' + Object.keys(entityMap.escape).join('') + ']', 'g'),
unescape: RegExp('(' + Object.keys(entityMap.unescape).join('|') + ')', 'g')
}
function escape(html) {
if (typeof html !== 'string') return ''
return html.replace(entityReg.escape, function (match) {
return entityMap.escape[match]
})
}
function unescape(str) {
if (typeof str !== 'string') return ''
return str.replace(entityReg.unescape, function (match) {
return entityMap.unescape[match]
})
}
let record = '<div class="news-item">.*?</div>'
let 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><div class="news-item"><h3 class="title">标题2标题2</h3><div>新闻概览2新闻概览2</div></div><div class="news-item"><h3 class="title">标题3标题3</h3><div>新闻概览3新闻概览3</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, 'g')
let records = sourceData.match(regRecord)
let str = ''
let splitedSourceList = sourceData.split(regRecord)
splitedSourceList.forEach((item, index) => {
if (index !== splitedSourceList.length - 1) {
let r = records[index]
let hightLightfield = r.replace(regField, '<span class="hight-light-field">' + escape(r) + '</span>')
str = str + escape(item) + hightLightfield
}else{
str = str + escape(item)
}
})
document.querySelector('.preview-wrapper').innerHTML = str
console.log(str)
}
<div class="preview-wrapper"></div>
.hight-light-field{
background: yellow;
}