【问题标题】:What is the easiest way to check if string contains any image tag?检查字符串是否包含任何图像标签的最简单方法是什么?
【发布时间】:2012-12-21 14:19:45
【问题描述】:

例如我有文字:

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

我想写一个函数来检查字符串中是否是img标签并返回true

【问题讨论】:

  • 最简单的是正则表达式,但它不会很健壮。

标签: javascript jquery


【解决方案1】:

使用正则表达式:

"testestestestt testestestes <img src='image.jpg'>".match(/<img/)

【讨论】:

  • 如何检查字符串是否包含带有文本的img标签
  • @PrajapatiJigar 你的意思是 alt 属性还是图片中的文字?
【解决方案2】:
var str = "testestestestt testestestes <img src='image.jpg'>";
var hasImg = !!$('<div />').html(str).find('img').length

【讨论】:

  • 这会在你添加到 div 时尝试加载图片。
  • 虽然这会在添加到 div 时尝试加载图像,但它是唯一实际检查是否存在 img 元素的答案,而不仅仅是字符串“img”或它的变体。
【解决方案3】:

显然,不建议使用正则表达式来解析 HTML,但是,根据您使用它的方式,您可能希望确保 img 标记具有相应的结束标记。这是一个稍微健壮的正则表达式:

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

匹配的测试用例:

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

不匹配的测试用例:

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

匹配后,您可以使用 XML 或 HTML 解析器轻松处理它,然后检查它是否具有 src 属性等。

【讨论】:

  • 嗯,对于这种 img 标签,我总是为空:testestestestestes &lt;img src="http://i.imgur.com/0kZ5U.png" /&gt;
  • @regedarek 确保你没有像 &lt;img src=".." /&gt;&lt;/img&gt; 这样的标签,因为如果你这样做 &lt;img /&gt; 就不需要结束标签 &lt;/img&gt;
【解决方案4】:

实际上,给出的答案很快,但他们可能会面临一些错误预测img tags 的特殊情况,例如I posted my &lt;picture&gt; in &lt;imgur&gt;

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

此外,在现代浏览器中,与this answer 配对的字符串中有更快的“

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

但最可靠的方法是要么使用完整的img tag regex-matcher,要么让浏览器执行它们已经完成的操作。

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 函数深受this answer 的启发

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    • 2012-07-13
    • 1970-01-01
    相关资源
    最近更新 更多