2

there is a string like

<img src="images/_attachments/07-08.jpg" style="width: 520px; height: 693px;" /><img src="images/_attachments/09-11.jpg" style="width: 520px; height: 693px;" />

I wanna get the image path 'images/_attachments/07-08.jpg', 'images/_attachments/09-11.jpg' and file name '07-08.jpg', '09-11.jpg' in javascript with regular expression.

So I code like

var str='<img src="images/_attachments/07-08.jpg" style="width: 520px; height: 693px;" /><img src="images/_attachments/09-11.jpg" style="width: 520px; height: 693px;" />'
var strPattern=new RegExp('<img.*?src="(.*\/(.*?))".*?>', 'g');
var arrMatch=new Array();
var strHTML='';

while(arrMatches=_strPattern.exec(str)){
    strHTML+='<div>'+arrMatches[2]+'</div>';
}

$('body').html(strHTML);

but all i get is path, not file name, how can i fix this?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Jana
  • 432
  • 4
  • 18

3 Answers3

1

Your path-matching is greedy, so you won't get the desired results for the file name. If you make it non-greedy, it will only match images/, so you either need to double it or make your filename matcher include no slashes. Change your pattern to

var strPattern=new RegExp('<img.*?src="(.*?\/([^/"]*))".*?>', 'g');
//                                        ^

Btw, a regex literal /<img.*?src="(.*?\/([^\/"]*))".*?>/g would look better.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

With this you are not matching the " or the >, maybe it helps?

var strPattern=new RegExp('<img [^>]*src="([^>"]+\/([^>"]+))"[^>]*?>', 'g');
Enfenion
  • 502
  • 3
  • 8
1

Use this pattern to match attribute contents:

_strPattern=new RegExp('<img.*?src="([^">]*\/([^">]*?))".*?>', 'g');

I you use '.' instead of '^">', the regex might span a few tags.

You also need to use _arrMatches[1] instead of _arrMatches[2] to get the full path.

hegemon
  • 6,614
  • 2
  • 32
  • 30