使用javascript或angularjs特定过滤器搜索字符串中第一个img标记的json值
在处理一个角度项目时,遇到了一种情况,其中一个端点不能准确地返回一个易于使用的图像对象 假设控制台中有一个json对象,它返回如下内容:使用javascript或angularjs特定过滤器搜索字符串中第一个img标记的json值,javascript,json,angularjs,Javascript,Json,Angularjs,在处理一个角度项目时,遇到了一种情况,其中一个端点不能准确地返回一个易于使用的图像对象 假设控制台中有一个json对象,它返回如下内容: __cdata: "Some random text here and <img src="image.jpg">" \uu cdata:“此处有一些随机文本,然后” 您将如何在\uuCDATA值中搜索第一个img标记并存储该src?我猜这在技术上也不一定是一个特定于角度的解决方案,但好奇是否存在。谢谢首先,如果您想让您的img src使用“双
__cdata: "Some random text here and <img src="image.jpg">"
\uu cdata:“此处有一些随机文本,然后”
您将如何在
\uuCDATA
值中搜索第一个img标记并存储该src?我猜这在技术上也不一定是一个特定于角度的解决方案,但好奇是否存在。谢谢首先,如果您想让您的img src
使用“双引号”,您需要将字符串用“单引号”而不是“双引号”括起来。否则,字符串将在src
标记处断开
无论如何,您可以利用string.indexOf:
var tagIndex = __cdata.indexOf('<img'); // Find where the img tag starts
var srcIndex = __cdata.substring(tagIndex).indexOf('src=') + tagIndex; // Find where the src attribute starts
var urlStart = srcIndex + 5; // Find where the actual image URL starts; 5 for the length of 'src="'
var urlEnd = __cdata.substring(urlStart).indexOf('"') + urlStart; // Find where the URL ends
var src = __cdata.substring(urlStart, urlEnd); // Extract just the URL
var tagIndex=\uu cdata.indexOf(“我认为最好的方法是使用RegExp:
var matches = String(text).match(/<img.*?src="([^"]*)"[^>]*>(?:<\/img>)?/m);
result = (matches && matches.length && matches[1]) ? matches[1] : '';
var matches=String(text).match(/]*>(?:)?/m);
结果=(matches&&matches.length&&matches[1])?matches[1]:“”;
Heyo!我也不太确定是否有一个角度特定的方法,但我能想到的只是做一个字符串搜索,并在src属性中找出位置。啊,哎呀。请原谅我的代码太草率。我们格雷格必须团结在一起!:)