jQuery.grep()匹配URL和www,非www,http / https

时间:2016-12-02 11:33:15

标签: javascript jquery json

我正在使用jquery在json字符串中搜索匹配的url,然后获取该对象内的所有数据。

我用

获取网址
var url = window.location.href;

然而,这会返回

http://somesite.com/

json字符串中的

可以是以下任何一种

等等。

我的代码是匹配网址,然后做一些事情。我如何使用jQuery.grep()来获取查询中的不同样式网址?以下是我目前的代码。

var url = window.location.href;
var json = exampleJsonString;
var js = JSON.parse(json);
var result = $.grep(js, function(e){ return e.url == url; });

if (result.length == 0) {
  // not found :(
  console.log('Not found');
} else if (result.length == 1) {
  // Result matched
  console.log(result);

} 

else {
  // multiple items found
  console.log('multiple items found');
  console.log(result); 
}

我想要做的是使用jquery grep检查somesite.com。如同在这一行中一样,它检查字符串是否相等。

var result = $.grep(js, function(e){ return e.url == url; }); 

1 个答案:

答案 0 :(得分:2)

您可以使用grep功能过滤记录。在您的情况下,您希望检查对象中的不同网址,例如' http://somesite.com/',' http://somesite.com'等,提及你想在grep函数中考虑的所有URL。这是示例代码。

   var varObj = jQuery.grep(dataobject, function (a) {
            if (a.url == "http://somesite.com/" || a.url == "http://somesite.com" || a.url == "http://www.somesite.com/")
                return true;
        });