Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to check if string contains any image tag?

For example I have text:

"testestestestt testestestes <img src='image.jpg'>"

I want to write function which check if in string is img tag and return true

like image 779
tomekfranek Avatar asked Jan 07 '13 19:01

tomekfranek


3 Answers

using regex:

"testestestestt testestestes <img src='image.jpg'>".match(/<img/)
like image 196
jcubic Avatar answered Nov 08 '22 04:11

jcubic


var str = "testestestestt testestestes <img src='image.jpg'>";
var hasImg = !!$('<div />').html(str).find('img').length
like image 21
keune Avatar answered Nov 08 '22 04:11

keune


Obviously, regular expressions are not recommend for parsing HTML, however, depending on the way you are using this, you may want to be assured that the img tag(s) have a corresponding ending tag. This is a slightly more robust regular expression for that:

if("<img>TestString</img>".match(/<img[^<]*>[\w\d]*<\/img>|<img[^\/]*\/>/i))
{
  alert('matched');
}
else
  alert('nope');

Matched Test Cases:

- blahsdkfajsldkfj<img blah src=\"\">iImmage123dfasdfsa</img>
- blahsdkfajsldkfj<img>iImmage123dfasdfsa</img>asdfas
- <img src=\"\"></img>
- <img></img>
- <img />

Unmatched Test Cases:

- <img (other regex would match this)
- <img>

Once you match it you can easily process it with an XML or HTML parser are then check if it has the src attribute etc.

like image 42
Alex W Avatar answered Nov 08 '22 03:11

Alex W