regex extract img src javascript

前端 未结 3 763
轮回少年
轮回少年 2021-01-06 17:41

I am trying to extract the img and src from a long html string.

I know there are a lot of questions about how to do this, but I have tried and gotten the wrong resu

相关标签:
3条回答
  • 2021-01-06 18:14

    If you need to get the whole img tags for some reason:

    const imgTags = html.match(/<img [^>]*src="[^"]*"[^>]*>/gm);
    

    then you can extract the source link for every img tag in array like this:

    const sources = html.match(/<img [^>]*src="[^"]*"[^>]*>/gm)
                              .map(x => x.replace(/.*src="([^"]*)".*/, '$1'));
    
    0 讨论(0)
  • 2021-01-06 18:18

    Try this:

    var match = regexp.exec(url);
    var src = match[1];
    
    0 讨论(0)
  • 2021-01-06 18:33

    Not a big fan of using regex to parse html content, so here goes the longer way

    var url = "<img height=\"100\" src=\"data:image/png;base64,testurlhere\" width=\"200\"></img>";
    var tmp = document.createElement('div');
    tmp.innerHTML = url;
    var src = tmp.querySelector('img').getAttribute('src');
    snippet.log(src)
    <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
    <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

    0 讨论(0)
提交回复
热议问题