リモートで働くプログラマーの検索結果

リモ太がググったことの覚書

javascriptでhtmlの文字列をパースしてimgタグのsrcを抜き出す

以下のような感じでsrcの中を取得する

const text = "<img src='http://example.com/image.png'>テスト画像"
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(text, 'text/html');
const img = htmlDoc.querySelector('img')
if (img) {
  console.log(img.src)
}

これを実行すると http://example.com/image.pngとlogに出力される