我正在获取一个json对象,该对象如下所示:
{
title: "My entry",
entry: "I am a paragraph. I have <em>italics</em> and other styling html.
I am the second paragraph.
I am the third graf, here is a <a href='#'>link</a>. "
}
然后,我使用模板文字追加页面上的对象,如下所示
const myJson = out.response.items.map((item, index) => {
return `<div data-item="${index}">
<h2>${item.title}</h2>
${item.entry}
</div>`;
});
content.innerHTML = myJson;
我遇到的问题是,我需要${item.entry}来观察JSON中的html和段落中断。我该怎么做?
可以使用以下正则表达式拆分条目
:/\s*\n\s*/g
null
const content = document.querySelector('.content');
const out = {
response: {
items: [{
title: "My entry",
entry: `I am a paragraph. I have <em>italics</em> and other styling html.
I am the second paragraph.
I am the third graf, here is a <a href='#'>link</a>.`
}]
}
};
const myHtml = out.response.items.map(({ title, entry }, index) => `
<div data-item="${index}">
<h2>${title}</h2>
${entry.trim().split(/\s*\n\s*/g).map(p => `<p>${p}</p>`).join('')}
</div>
`).join('');
content.innerHTML = myHtml;
<div class="content"></div>