How do I extract the image src from this string by pattern matching?
var str = "<img src=\"http://l.yimg.com/a/i/us/we/52/20.gif\"/><br />\n<b>
Current Conditions:</b><br />\nFog, 16 C<BR />\n<BR /><b>";
?
How do I extract the image src from this string by pattern matching?
var str = "<img src=\"http://l.yimg.com/a/i/us/we/52/20.gif\"/><br />\n<b>
Current Conditions:</b><br />\nFog, 16 C<BR />\n<BR /><b>";
?
Since you are in JavaScript, you have a DOM parser readily available. Use it.
var tmp = document.createElement('div');
tmp.innerHTML = str;
var img = tmp.getElementsByTagName('img')[0];
var src = img.src;
Done ^_^
A working example to use regular expressions:
<script>
var str = "<img src=\"http://l.yimg.com/a/i/us/we/52/20.gif\"/><br />\n<b>";
var regex = /(http|ftp|https):\/\/([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/
var url = str.match(regex)[0];
alert(url);
</script>
Used the regex string from here: Regular expression to find URLs within a string
It has to be by pattern matching? With jquery:
var src = $('img').attr('src');
You should consider using jquery for that. If you have you html on a string, then just do
$('<div>' + myHtml + '</div>').find('img').attr('src');
To parse it. If you are not using jquery, you could try something like:
new DOMParser().parseFromString(myHtml, "text/html");
With plain js to get the dom.