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
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
using regex:
"testestestestt testestestes <img src='image.jpg'>".match(/<img/)
var str = "testestestestt testestestes <img src='image.jpg'>";
var hasImg = !!$('<div />').html(str).find('img').length
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.
``
– tomekfranek
Jan 08 '13 at 17:44
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