Javascript:检测字符串是否包含网址图片

时间:2015-05-26 08:44:23

标签: javascript regex parsing

我有以下字符串:

var str = "Hello, i would like to show this image : http://logonoid.com/images/stack-overflow-logo.png" ;

我想创建一个函数来检测图片网址的存在并返回两件事:

  • 没有图片网址的新字符串
  • 包含在字符串中找到的图像网址的数组。

我该怎么做?

5 个答案:

答案 0 :(得分:1)

您可以尝试这样的方法,我正在检查图像文件扩展名

var str = "Hello, i would like to show this image : http://logonoid.com/images/stack-overflow-logo.gif" ;
var test = (/\.(gif|jpg|jpeg|tiff|png)$/i).test(str)

如果找到匹配项,则会返回true,否则为false

Fiddle

答案 1 :(得分:0)

你熟悉正则表达式吗?因为你问的东西很简单: 检测URL的正则表达式是

^(http|https)://

并在Javascript中:

str.match(^(http|https)://);

现在由您决定如何保存正确的输出。

答案 2 :(得分:0)

您可以使用以下内容进行匹配:

(https?:[^\s]+)
  • 第1组将提供网址列表..您可以使用''空字符串替换它们以获取新字符串。

请参阅DEMO

答案 3 :(得分:0)

简单的方式看起来像那样

var str = "Hello, i would like to show this image : http://logonoid.com/images/stack-overflow-logo.png" ;
console.log(str.includes(":"));


if(str.includes(":") && ( (str.includes("http") || str.includes("https")) )){
  var newOutput = str.split(":");
  for(var i in newOutput){
  console.log("[" + i + "]: " + newOutput[i]);
  }

  var message= newOutput[0];
  var urlImage= newOutput[1] + newOutput[2];

  console.log("message: " + message +" , URL: " + urlImage);
}else{
 console.log("no URL find");
}

你可以使用匹配"如果"它看起来会更好:o)

答案 4 :(得分:0)

我认为最短的方法:

console.log(newVal.match(/\.(jpeg|jpg|png|gif)/g) != null);

如果找到匹配项,则返回 true ,否则返回 false