如何获取html元素标签的内容

问题描述 投票:0回答:1

可以使用typescript只获取字符串中 "n "元素标签的上下文。

string = "<h1>Just survive</h1><p>Of such great powers or beings there may be conceivably a survival... a survival of a hugely remote period when . . . consciousness was manifested, perhaps, in shapes and forms long since withdrawn before the tide of advancing humanity . . . forms of which poetry and legend alone have caught a flying memory and called them gods, monsters, mythical beings of all sorts and kinds...</p>"

想要输出。

在这种伟大的力量或生命中,可能有一个可以想象的生存... ...一个遥远的时期的生存... ...意识被表现出来,也许,在人类进步的大潮之前,它的形状和形式早已消失了... ...其中的形式,只有诗歌和传说能捕捉到一个飞翔的记忆,并称它们为神,怪物,各种神话生物... ...。

typescript
1个回答
0
投票

你可以用DOMParser把HTML字符串变成一个元素,然后把它的 textContent:

const string = "<h1>Just survive</h1><p>Of such great powers or beings there may be conceivably a survival... a survival of a hugely remote period when . . . consciousness was manifested, perhaps, in shapes and forms long since withdrawn before the tide of advancing humanity . . . forms of which poetry and legend alone have caught a flying memory and called them gods, monsters, mythical beings of all sorts and kinds...</p>"
const doc = new DOMParser().parseFromString(string, 'text/html');
console.log(doc.body.textContent);
© www.soinside.com 2019 - 2024. All rights reserved.