简体   繁体   中英

find first sequence of “/>” in regExp, javascript

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

您可以尝试使用'?'使正则表达式不贪心:

var regXstr = "<img (.)*?/>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM