javascript - 将 String html 转换为数组对象类型

标签 javascript regex react-native

我有字符串内容 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/

相关文章:

javascript - 在 asp.net 中无法看到 JSColor 对象中的颜色面板

react-native - 任务 ':app:compileDebugJavaWithJavac' 执行失败。 react 原生

regex - Notepad++ 删除非字母数字字符

reactjs - 依赖项与安装的expo包版本不兼容,找不到模块 'nocache'

javascript - React Native 中心动画图标

c# - 如何运行 DropDownList 更改事件

javascript - 如何在单击时更改 ListItem 的样式?

javascript - 运行 Node 程序时出错。模块 'prompt' 不工作

javascript - 如何查找以特定字母开头的单词?

regex - 用于修改开头仅包含单个单词的行的正则表达式