javascript - 使用正则表达式验证数组中的多个邮政编码
问题描述
我正在尝试创建一个针对正则表达式验证邮政编码的函数。用户可以使用一个邮政编码或多个邮政编码。
当我输入一个邮政编码时,它工作正常,但是当输入多个邮政编码时,我只是不确定
这是我的功能
const validatePostcode = (...postcode) => {
const postcodeRegex = /^[A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1} ?[0-9][A-Z]{2}$/i;
if (postcode.length > 1) {
postcode.forEach((item) => {
console.log(item);
return postcodeRegex.test(item);
});
} else {
return postcodeRegex.test(postcode);
}
};
解决方案
forEach 方法并不意味着返回任何值:lambda 的返回值被丢弃。这就是你不确定的原因。if... else...
也无用。forEach 适用于一个元素的数组。您需要一个接收 lmbda 并返回值的函数。取决于您想要的every
,(如果所有邮政编码都匹配,则返回 true,请参阅@ttquang1063750 的回答)或者map
(返回一个布尔数组,每个传递的邮政编码一个)或some
(如果至少一个邮政编码匹配,则返回 true)
const validatePostcode = (...postcode) => {
const postcodeRegex = /^[A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1} ?[0-9][A-Z]{2}$/i;
return postcode.map(item => postcodeRegex.test(item));
};
const validateAtLeastOnePostcode = (...postcode) => {
const postcodeRegex = /^[A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1} ?[0-9][A-Z]{2}$/i;
return postcode.some(item => postcodeRegex.test(item));
};
推荐阅读
- javascript - V-Model 中的条件语句
- math - 求解递归:T(n) = T(n - 1) + T(n - 2) + 3
- javascript - 根据传递的 props 为组件创建类型
- reactjs - 如何为 react-select 组件的每个选项设置不同的样式?
- opc-ua - 什么是 OPC-UA 中的节点?
- javascript - 扩展js原型,参数被强制类型
- c - sys/time.h 定时器只运行一次
- python - 如何将工作组信息传递给 Boto3 中的 Athena startQueryExecution 方法
- javascript - 如何在 React 中单击按钮时动态呈现组件中的用户数据
- java - 在 MapReduce Iterable IntWritable 中对正数和负数求和