jQuery.grep() match URL both www and non www, http/https



我正在使用jQuery搜索匹配的URL的JSON字符串,然后获取该对象中的所有数据。

我用

获取URL
var url = window.location.href;

但是,这返回

http://somesite.com/

在JSON字符串中可以是以下任何一个

  • http://somesite.com/
  • http://somesite.com
  • http://www.somesite.com/
  • http://www.somesite.com https://somesite.com/

等等。

我的代码是匹配URL,然后做某事。我将如何使用jquery.grep()在查询中使用不同的样式URL?以下是我到目前为止的代码。

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; }); 

您可以使用GREP功能过滤记录。在您的情况下,您希望在" http://somesite.com/'http://somesite.com"等中检查对象中的其他URL,例如,提及您在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;
        });

最新更新