1

I am trying to extract img's src using javascript's regexp yet I am not able to use the groups. I have came up with something like this so far :

>str
"xxxxx src="http://www.omgubuntu.co.uk/wp-content/uploads/2013/12/Multim.jpg" xxxxx"
>str.match(re)
["src="http://www.omgubuntu.co.uk/wp-content/uploads/2013/12/Multim.jpg""]
>re
/src=\"(.*?)\"/g
>str.match(re)[1]
undefined

Yet I only get the match for the whole pattern

3 Answers 3

1

Unsure why you'd want to do this with regex;

Simply use:

document.getElementById('idOfImgElement').src;

Or easier, with jQuery:

$('#idOfImgElement').attr(src);

But if you really want to do this with regex, use:

var str = "<img src=\"http://www.omgubuntu.co.uk/wp-content/uploads/2013/12/Multim.jpg\" />";
var matches = (/src=\"(.*?)\"/g).exec(str);
window.print(matches[1]);
Sign up to request clarification or add additional context in comments.

1 Comment

I am parsing the stream with html tags for processing that's why I cannot use DOM
1

How many possible img tags might be in your string? Assuming 1 then forget the global flag (and iterating through an exec) and simply make a regex that explains the whole string and use capture groups. Then you can specify, in your index of match, to return the capture group you know will represent it. Since, in these types of questions, there always seems to be a caveat not mentioned I made the expression more tight against some possibilities like other attributes in the element. So just in case it is more complex than you let on you can use this regex:

 (?:<img )?[^>]+src=(["'])(.*)\1

The quote capture group is necessary so that you match up the quotes. You show double quotes but is that guaranteed? in this regexThe second capture group is always going to be the URL (contents of src to be more precise).

In code:

var str = '<img src="http://www.omgubuntu.co.uk/wp-content/uploads/2013/12/Multim.jpg" />';
var src = str.match(/(?:<img )?[^>]+src=(["'])(.*)\1/)[2]

Comments

0

I have achieved this with regexp without gm flags

    var re_imgsrc = /.*src=\"(.*?)\".*/
    imageUrl = str.replace(re_imgsrc, "$1");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.