5

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

jcubic
  • 61,973
  • 54
  • 229
  • 402
tomekfranek
  • 6,852
  • 8
  • 45
  • 80

4 Answers4

10

using regex:

"testestestestt testestestes <img src='image.jpg'>".match(/<img/)
jcubic
  • 61,973
  • 54
  • 229
  • 402
2
var str = "testestestestt testestestes <img src='image.jpg'>";
var hasImg = !!$('<div />').html(str).find('img').length
keune
  • 5,779
  • 4
  • 34
  • 50
  • This will try to load the image when you add it to the div. – gen_Eric Jan 07 '13 at 19:55
  • 2
    Although this will try to load the image when added to the div, it's the only answer that actually checks for the existence of an img element rather than just a string "img" or a variation of that. – sachleen Jan 07 '13 at 19:58
1

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.

Alex W
  • 37,233
  • 13
  • 109
  • 109
0

Actually, given answers are fast, but they may face some special cases which mispredict img tags e.g. I posted my <picture> in <imgur>

`I posted my <picture> in <imgur>`.match(/<img/)
// ["<img", index: 25, ...]

also, there is a faster version of '<img' keyword search in a strings duo to this answer in modern browsers.

"testestestestt <img src='image.jpg'>".indexOf('<img') > -1

But the most reliable method is either you use a full img tag regex-matcher or let the browsers do things they've already done.

const hasImage = htmlString => {
  var div = document.createElement('div');
  div.innerHTML = htmlString

  return Boolean(div.querySelector('img'));
}

// tests
hasImage("testestestestt <img src='image.jpg'/>")
// true
hasImage("testestestestt <img src='image.jpg/>")
// false
hasImage("I posted my <picture> in <imgur>")
// false

hasImage function is highly inspired by this answer

amirhe
  • 2,186
  • 1
  • 13
  • 27