1

I want to find an img tag in a string. I wrote for example:

var str ='<img border="1" height="165" id="img2" src="http://google.jpg"  />';
var regXstr = "<img (.)*/>";
var regX = new RegExp(regXstr , 'gi');
document.write(str.match(regX));

and the output is the whole text in str which is good in this case, but the if I switch the str with the following:

var str ='<img border="1" height="165" id="img2" src="http://google.jpg" /> /> />';

or with

var str ='<img border="1" height="165" id="img2" src="http://google.jpg"  /><span/>';

the result is still the whole text in str, and I want only the img tag - from <img till first />

adl
  • 1,865
  • 1
  • 25
  • 32

1 Answers1

1

You can try making the regex not-greedy using '?':

var regXstr = "<img (.)*?/>";
adl
  • 1,865
  • 1
  • 25
  • 32
PinnyM
  • 35,165
  • 3
  • 73
  • 81
  • great. Thanks! can you explain me what the '?' is doing in this case? I know it is for marking a single character – adl Feb 22 '12 at 20:00
  • using a '?' after a '+' or '*' tells the matcher to search for the smallest match, see http://www.javascriptkit.com/javatutors/redev2.shtml – PinnyM Feb 22 '12 at 20:03
  • The second pattern will will only match the string `""` because you're missing a `.` or anything that would actually consume a character. – Mike Samuel Feb 22 '12 at 20:05