CLiown CLiown - 1 month ago 8
Javascript Question

substring/regex to get a src value held in a string

I have a string with the value:

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>"


I'd like to take the
URL
held in the
src
attribute part of the string if possible.

How can I do this using JavaScript?

Answer

One way to do it is to use regular expressions.

var str = "<img alt='' src='http://api.com/images/UID' /><br/>Some plain text<br/><a href='http://www.google.com'>http://www.google.com</a>";

var regex = /<img.*?src='(.*?)'/;
var src = regex.exec(str)[1];

console.log(src);