正则表达式提取img src javascript [英] regex extract img src javascript
问题描述
我试图从一个长html字符串中提取img和src。
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 result. My question is just about contradicting results though.
我正在使用:
var url = "<img height=\"100\" src=\"data:image/png;base64,testurlhere\" width=\"200\"></img>";
var regexp = /<img[^>]+src\s*=\s*['"]([^'"]+)['"][^>]*>/g;
var src = url.match(regexp);
但是这个结果在src中没有被正确提取。我一直得到src = < img height =100src =data:image / png; base64,testurlherewidth =200>< / img> ;
而不是数据:image / png; base64,testurlhere
But this results in src not being extracted properly. I keep getting src =<img height="100" src="data:image/png;base64,testurlhere" width="200"></img>
instead of data:image/png;base64,testurlhere
然而,当我在regex101上的regex测试器上试试这个,它正确地提取了src。我做错了什么?是 match()
使用错误的函数>
However, when I try this on the regex tester at regex101, it extracts the src correctly. What am I doing wrong? Is match()
the wrong function to use>
推荐答案
不是使用正则表达式解析html内容的忠实粉丝,所以这里有更长的路要走
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>
这篇关于正则表达式提取img src javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!