如何使用javascript通过不区分大小写的搜索从JSON返回结果?

Vis*_*bia 1 javascript regex search json case-insensitive

我的JSON包含"产品",每个产品都有多个值(名称,制造商等)

我有以下代码,允许我根据从查询字符串中获取的搜索结果从我的JSON中提取"产品".它工作正常,但只有在搜索条目的格式完全如何在字符串中写入.

如何允许不区分大小写的搜索产生所需的结果(理想情况下,部分搜索)?

我相信正则表达式是可行的方式,但我已经耗尽了我的知识,似乎无法随意使用它.

我试图把一个小提琴放在一起,但无法得到一个正确的演示工作,所以相反,我试图巩固代码并评论它的清晰度.任何帮助将不胜感激 :)

解析JSON:

var prodobjects = JSON.parse(prods);
Run Code Online (Sandbox Code Playgroud)

根据具体价值获取产品的代码:

function getData(array, type, val) {
  return array.filter(function (el) { 
    return el[type] === val;
  });
}
Run Code Online (Sandbox Code Playgroud)

检索查询字符串的代码:

function gup( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
var regexS = "[\\?&]"+name+"=([^&#]*)";  
var regex = new RegExp( regexS );  
var results = regex.exec( window.location.href ); 
 if( results == null )    return "";  
else    return results[1];}
Run Code Online (Sandbox Code Playgroud)

我想要使​​用的查询字符串部分:

var prodresult = gup( 'search' );   
Run Code Online (Sandbox Code Playgroud)

删除加号并替换为空格:

var removeplus = prodresult.replace(/\+/g, ' ');
Run Code Online (Sandbox Code Playgroud)

使用与"搜索"查询匹配的"产品名称"编译产品列表:

var searchname = getData(prodobjects.products, 'Prodname', removeplus);
Run Code Online (Sandbox Code Playgroud)

这里要求的是JSON的示例.它仍在开发中,因此目前正在制定空值等(它是通过api接收的).这只是其中一个产品,但实际的字符串包含许多相同格式(但在"产品"中):

var prods = JSON.stringify({"products": [
    {
        "Prodname": null,
        "Oem": "Example OEM",
        "Snippet": "Example Snippet",
        "Linkto": "www.linkhere.com",
        "Imagesource": "image.png",
        "Category": "Category",
        "Tagline": "Tagline goes here",
        "Longdescription": [
            {
                "Paragraph": "<p>First description of the paragraph</p>"
            },
            null,
            null,
            null
        ],
        "Features": null,
        "Company": false,
        "Subscribed": false,
        "Tariffs": [
            {
                "Tarname": "Tariff one",
                "Tarpaysched": "Monthly per User",
                "Tarcost": "£1"
            },
            null,
            null,
            null,
            null,
            null
        ],
        "Extratariffs": null
    }
]
});
Run Code Online (Sandbox Code Playgroud)

--- UPDATE ---

我设法通过以下方式使其支持部分搜索和不区分大小写:

function getData(array, type, val) {
  return array.filter(function (el) {
      if (el[type]!=null && val!=null) {
          var seeker = val.toLowerCase();
          var rooted = el[type].toLowerCase();
          var boxfresh = rooted.indexOf(seeker);
          if (boxfresh!=-1) {
              return rooted
          }
      }
  });
}
Run Code Online (Sandbox Code Playgroud)

Bri*_*and 5

您可以将两个字符串转换为小写(或大写),以使比较不区分大小写.

function getData(array, type, val) {
  return array.filter(function (el) { 
    return el[type].toLowerCase() === val.toLowerCase();
  });
}
Run Code Online (Sandbox Code Playgroud)

为了更好的搜索,您可能需要查看模糊比较,即"搜索数据以确定可能的误导和近似字符串匹配".