One approach, is the following:
var string = "<img alt='' src='http://api.com/images/UID' /><br/>Some plain text<br/><a href='http://www.google.com'>http://www.google.com</a>",
srcWithQuotes = string.match(/src\=([^\s]*)\s/)[1],
src = srcWithQuotes.substring(1,srcWithQuotes.length - 1);
console.log(src);
JS Fiddle demo.
This effectively matches a sequence of characters starting with src=
(the =
is escaped with a back-slash because, otherwise, it holds special meaning within regular expressions), followed by a sequence of non-white-space characters (^\s*
) followed by a white-space character (\s
).
This expression explicitly captures the quotes used to delimit the src
attribute, the src
is returned by taking a substring of the srcWithQuotes
variable, starting at 1
(the first, the zeroeth, character should be the attribute delimiter) until the index before the last character (the final quote delimiting the attribute).
There is a slightly convoluted (but potentially more reliable) approach, using a document fragment:
var string = "<img alt='' src='http://api.com/images/UID' /><br/>Some plain text<br/><a href='http://www.google.com'>http://www.google.com</a>",
temp = document.createElement('div'),
frag = document.createDocumentFragment();
temp.innerHTML = string;
frag.appendChild(temp);
console.log(temp.getElementsByTagName('img')[0].src);
JS Fiddle demo.
Of course, in this example, you could use any approach you like to find the image within the temp
node (getElementById()
, getElementsByClassName()
...).