javascript - 如何过滤英国邮政编码
问题描述
我正在尝试将英国邮政编码的第一部分与我保存在 JSON 文件中的部分相匹配。我在 Vue 中这样做。
目前我已经设法匹配邮政编码,如果它有 2 个匹配的字母,但是一些英国邮政编码不以 2 个字母开头,有些只有一个,这就是它失败的地方。
完整代码见这里 https://codesandbox.io/s/48ywww0zk4
JSON 示例
{
"id": 1,
"postcode": "AL",
"name": "St. Albans",
"zone": 3
},
{
"id": 2,
"postcode": "B",
"name": "Birmingham",
"zone": 2
},
{
"id": 3,
"postcode": "BA",
"name": "Bath",
"zone": 5
}
let postcodeZones = this.postcodeDetails.filter(
pc => pc.postcode
.toLowerCase()
.slice(0, 2)
.indexOf(this.selectPostcode.toLowerCase().slice(0, 2)) > -1
);
如果我输入 B94 5RD 和 'BA' 如果我输入 BA33HT,谁能帮我找到(例如)'B'?
解决方案
You can use a regular expression that matches the alphabetical letters at the start of a string.
function getLettersBeforeNumbers( postcode ) {
return postcode.match( /^[a-zA-Z]*/ )[0];
}
let a = getLettersBeforeNumbers( 'B94 5RD' );
let b = getLettersBeforeNumbers( 'bA33HT' );
let c = getLettersBeforeNumbers( '33bA33HT' );
console.log( a, b, c );
/** EXPLANATION OF THE REGEXP
/ ^[a-zA-Z]* /
^ = anchor that signifies the start of the string
[ ... ] = select characters that are equal to ...
a-z = all characters in the alphabet
A-Z = all capatilised characters in the alphabet
* = zero or more occurances
**/
PS: You can just use the .match( /^[a-zA-Z]*/ )[0];
on your string.
推荐阅读
- java - 如何按具有 ID 的员工的值对 HashMap 进行排序?
- linux - 接口、配置和端点是这些软件实体或硬件
- swift - 如何将0/1的二进制表示字符串转换为字符串?
- python - 在python中查找出现在k个以上集合中的元素
- windows - vmware 工作站 15 播放器:设备/凭据保护不兼容问题甚至禁用它
- asp.net - 如何提高 ASP.NET Web 应用程序开发的效率?
- spring-integration - 如何使用 Zookeeper 和 Spring 集成负载平衡领导者
- read-the-docs - 如何在 Mac OS X 上本地测试 github repo mkdocs 构建的文件?
- c# - ServiceStack.Text model.ToCsv() 没有将输出属性用引号括起来
- hosting - 通过 BitBucket Pipelines 通过 TLS 进行 FTP