jQuery 部分数组匹配用户输入?



我一直在研究邮政编码检查器,我需要在数组上进行部分匹配。 即:如果用户当前使用 L20,则显示真,但如果使用 L20 1WE 如果显示假。

我需要它来读取数组,如果用户输入的任何部分匹配,则显示 true。

我这里有一个演示:https://codepen.io/paulmaloney/pen/dfa0603f200a8f5be89b0a10d7ba80f6

var postcodes = ["PR8","PR9","WA11","L1","L2","L20","L80"];
$('#searchForm').submit(function(){
var postcode = $('#searchForm input').val();  
if($.inArray(postcode.toUpperCase(), postcodes ) > -1){
$('#result').html('Yes, we cover your area!');
}else{
$('#result').html('Sorry, it looks like we do not cover that area yet.');
}
return false;
});

到目前为止,这是我的代码。我知道我错过了一些愚蠢的东西,但无法解决

您可以拆分输入,然后按以下方式使用some()includes()

var postcodes = ["PR8","PR9","WA11","L1","L2","L20","L80"];
$('#searchForm').submit(function(){
var postcode = $('#searchForm input').val().toUpperCase();
postcode = postcode.trim().includes(' ') ? postcode.split(' ') : postcode.match(/.{1,3}/g);
if(postcode.some(i => postcodes.includes(i))){
$('#result').html('Yes, we cover your area!');
}else{
$('#result').html('Sorry, it looks like we do not cover that area yet.');
}
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="search" id="searchForm">
<input type="text" name="s" class="form-control covered-area-search-input" placeholder="Enter the first half of your postcode...">
<input type="submit" value="Search"/> 
</form>
<div id="result"></div>

也许,不需要拆分和匹配。只需检查当前值是否包含数组的任何项。

var postcodes = ["PR8","PR9","WA11","L1","L2","L20","L80"];
$('#searchForm').submit(function(){
var postcode = $('#searchForm input').val().toUpperCase();
if(postcodes.some(i => postcode.includes(i))){
$('#result').html('Yes, we cover your area!');
}else{
$('#result').html('Sorry, it looks like we do not cover that area yet.');
}
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="search" id="searchForm">
<input type="text" name="s" class="form-control covered-area-search-input" placeholder="Enter the first half of your postcode...">
<input type="submit" value="Search"/> 
</form>
<div id="result"></div>

$.inArray 在数组postcodespostcode和值之间进行严格检查。

由于您要检查用户输入的postcode是否以数组中的任何postcode为前缀postcodes因此您需要为此编写自定义过滤器。

postcode数组中找到每个匹配的邮政编码到邮政编码条目的第一部分。

postcodePart = postcode.toUppercase().split(' ').shift()
matches = postcodes.filter(
postcode => new RegExp("^" + postcode + "$").test(postcodePart)
)

检查匹配的邮政编码的长度并验证是否存在匹配。

if (matches.length == 1) {
$('#result').html('Yes, we cover your area!');
} else {
$('#result').html('Sorry, it looks like we do not cover that area yet.');
}

最新更新