简体   繁体   English

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

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

I am using jquery to search a json string for the matched url and then fetch all the data inside that object. 我正在使用jquery搜索匹配的URL的json字符串,然后获取该对象内的所有数据。

I fetch the url with 我用

var url = window.location.href;

However this returns 但是,这返回

http://somesite.com/ http://somesite.com/

inside the json string could be any of the following json字符串中可能是以下任何内容

etc etc. 等等等

My code is to match the url and then do something. 我的代码是匹配url,然后执行某些操作。 How would I go about using jQuery.grep() to take the different style urls in the query? 我将如何使用jQuery.grep()在查询中采用不同的样式网址? Below is my code so far. 下面是到目前为止的代码。

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

What I want to do is check for somesite.com using jquery grep. 我想做的是使用jquery grep检查somesite.com。 As in this line it checks if the string is equal. 如该行所示,它检查字符串是否相等。

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

You can use grep function to filter the records. 您可以使用grep函数来过滤记录。 Here in your case want to check different URL's in the object like ' http://somesite.com/ ',' http://somesite.com ' etc, mention all the URL's that you want to consider in grep function. 在这里,您要检查对象中的不同URL,例如“ http://somesite.com/ ”,“ http://somesite.com ”等,并提及您要在grep函数中考虑的所有URL。 Here is the sample code. 这是示例代码。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM