David 天宇 Wong
David 天宇 Wong

Reputation: 4187

Javascript regex match doesn't run correctly

okay I give up. Here's my code:

var re = /href="(http.*\.jpg)"/g;
var mp3s = body.match(re);

it finds pictures, but it returns href="http://www.picture.com/smthg.jpg"

instead of returning http://www.picture.com/smthg.jpg

any idea why?

Upvotes: 0

Views: 51

Answers (3)

Andrew Shepherd
Andrew Shepherd

Reputation: 45232

You want to match the regular expression, but then return just the portion in brackets.

To do this, call the regular expressions exec method. For example:

var body = 'stuff stuff morestuff href="http://www.picture.com/smthg.jpg" and some more stuff';
var re = /href="(http.*\.jpg)"/g;
var regexResults = re.exec(body);
var mp3s = regexResults[1];
alert(mp3s);

Having given you this answer, I must implore you to find a different way to solve this problem. You cannot parse HTML using regular expressions. No matter how sophisticated your regular expression gets, there will be a legal HTML example which will break it.

Upvotes: 0

Felipe
Felipe

Reputation: 11887

The result from match() is actually an object.

I think you need to access the first element on that object.

For example:

body.match(re)[1]

This is where the actual result is kept.

Shameless self-promotion: I've written a small guide for me, I can never remember how to use these either. It's here: http://queirozf.com/reminders/javascript-regular-expressions-usage-reminder

Upvotes: 2

Abhas Tandon
Abhas Tandon

Reputation: 1889

try

var re = /(http.*\.jpg)/g;
var mp3s = body.match(re);

since you don't need the href.

Upvotes: 0

Related Questions