如何從HTML字符串中提取Img、video的標簽和地址


getImageAndVideoURL (con) {
    let obj = {}

    const imgReg = /<img.*?(?:>|\/>)/gi // 匹配圖片中的img標簽
    const videoReg = /<video(([\s\S])*?)<\/video>/gi // 匹配圖片中的img標簽
    const srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i // 匹配圖片中的src
    const ImageArr = con.match(imgReg) || [] // 篩選出所有的img
    const VideoArr = con.match(videoReg) || [] // 篩選出所有的video

    const indexImg = con.search(imgReg)
    const indexVideo = con.search(videoReg)
    // 去除所有圖片和視頻后的帖子內容
    const narrowHandle = con.replace(/&nbsp;/gi, '').replace(/<img.*?(?:>|\/>)/gi, '').replace(/<video(([\s\S])*?)<\/video>/gi, '').replace(/<p(.*)><\/p>/gi, '').replace(/<[^<>]+>/g, '')
    const ImageSrcArr = [] // 圖片地址數組
    const VideoSrcArr = [] // 視頻地址數組

    for (let i = 0; i < ImageArr.length; i++) {
      const imgSrc = ImageArr[i].match(srcReg)
      // 獲取圖片地址
      ImageSrcArr.push(imgSrc[1])
    }
    for (let i = 0; i < VideoArr.length; i++) {
      const videoSrc = VideoArr[i].match(srcReg)
      // 獲取圖片地址
      VideoSrcArr.push(videoSrc[1])
    }

    let haveImageOrVideo = false
    let showImageOrVideo = ''
    if (indexImg === -1 && indexVideo === -1) {
      haveImageOrVideo = false
    } else if (indexImg > 0 && indexImg < indexVideo) {
      haveImageOrVideo = true
      showImageOrVideo = 'IMG'
    } else if (indexImg > 0 && indexVideo < 0) {
      haveImageOrVideo = true
      showImageOrVideo = 'IMG'
    } else if (indexVideo > 0 && indexVideo < indexImg) {
      haveImageOrVideo = true
      showImageOrVideo = 'VIDEO'
    } else if (indexVideo > 0 && indexImg < 0) {
      haveImageOrVideo = true
      showImageOrVideo = 'VIDEO'
    }
    obj = {
      ImageSrcArr,
      VideoSrcArr,
      haveImageOrVideo,
      showImageOrVideo,
      narrowHandle,
      showLeft: true
    }
    return obj
  }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM