0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

生HTMLからタグを除去する

Last updated at Posted at 2022-05-04

vuev-htmlReactdangerouslySetInnerHTMLに出力させているHTMLのテキスト部分だけ必要な場面があったので備忘録

TLDR

const removalTag = (html: string) => {
 const domParser = new DOMParser()
 const doc = domParser.parseFromString(html, "text/html")
 return doc.body.innerText
}

解説

DOMParserの呼び出し

const domParser = new DOMParser()
const doc = domParser.parseFromString(html, "text/html")

第一引数にHTML、第二引数にtext/htmlを渡す。
ここについてはドキュメントの通り。

domParser.parseFromString()からの結果が<html><head></head><body></body></html>なのだが、
今回必要なテキスト部はbodyタグ配下に来るので一旦bodyで絞り込む。

テキストを抽出する

return doc.body.innerText
  • もしエスケープ文字(改行やタブ)が欲しい場合はinnerTexttextContentにする

おわりに

別にreplace()でも実現出来ないことはなさそうだけど、
大なり小なりとかエスケープを完全に考慮できた正規表現に自信が無いときにはアリかと思う。

(そもそもHTML埋め込む要件自体が無ければベスト)

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?