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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With