我有字符串内容 html 示例:
Yjgbhg <img id="image1" src="https://dzlvqfm687ile.cloudfront.net/5940_image-0878eae8-e316-46fc-a776-b3d22e292c55.jpg">Huyju <video src="https://dzlvqfm687ile.cloudfront.net/5824_video.mp4" id="video1" onclick="blurEditor();" onplay="blurEditor();" controls=""></video>
我想将字符串传递给相同的对象
[
{
type: "text",
value: "Yjgbhg"
},
{
type: "img",
value: "https://dzlvqfm687ile.cloudfront.net/5940_image-0878eae8-e316-46fc-a776-b3d22e292c55.jpg"
},
{
type: "text",
value: "Huyju"
},
{
type: "text",
value: "https://dzlvqfm687ile.cloudfront.net/5824_video.mp4"
},
]
我尝试使用
var regexp = /<img[^>]*src="?([^"\s]+)"?\s*\/>/g;
console.log(regexp.exec( strHtml ));
while ( m = regexp.exec( text ) ) {
urls.push( m[0] );
}
var regexp = /<video[^>]*src="?([^"\s]+)"?\s*\/>/img;
while ( m = regexp.exec( text ) ) {
urls.push( m[0] );
}
console.log(urls);
获取图像和视频,但返回数组为空。 我该怎么做?
最佳答案
使用 DOMParser
可能会容易得多:
const input = `Yjgbhg <img id="image1" src="https://dzlvqfm687ile.cloudfront.net/5940_image-0878eae8-e316-46fc-a776-b3d22e292c55.jpg">Huyju <video src="https://dzlvqfm687ile.cloudfront.net/5824_video.mp4" id="video1" onclick="blurEditor();" onplay="blurEditor();" controls=""></video>`;
const parser = new DOMParser().parseFromString(input, 'text/html');
const text1 = parser.body.childNodes[0].textContent.trim();
const img = parser.body.children[0].src;
const text2 = parser.body.childNodes[2].textContent.trim();
const video = parser.body.children[1].src;
console.log([text1, img, text2, video]);
关于javascript - 将 String html 转换为数组对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51297218/