提问人: 提问时间:10/4/2023 更新时间:10/4/2023 访问量:66
我的字符串检查不起作用,我不知道最有效的方法是什么
My string check doesnt work and I dont know what is the most eficient method to do it
问:
所以我有一个代码来检查字符串是否与某个模式匹配,这个模式:
555-555-5555
(555)555-5555
(555) 555-5555
555 555 5555
5555555555
1 555 555 5555
例如,这应该返回 true:
1 456 789 4444
但事实并非如此,这是我的代码:
function telephoneCheck(str) {
str = str.split('');
for (let c in str) {
if (str[c].match(/[0-9]/) && str[c] !== '5') {
str.splice(c, 1, 5);
console.log(str)
}
if (str.join('') === '555-555-5555' |str.join('') === '(555)555-5555' |str.join('') === '(555) 555-5555' |str.join('') === '555 555 5555' |str.join('') === '5555555555' |str.join('') === '5 555 555 5555') {
return true
}
return false
}
}
console.log(telephoneCheck("1 456 789 4444"));
正如你所看到的,我这样做的方式是干的
我正在检查它何时匹配模式以返回 true 否则 false,我不确定实际发生了什么
答:
1赞
Konrad
10/4/2023
#1
我会将其转换为正则表达式
const regex = new RegExp(`555-555-5555
(555)555-5555
(555) 555-5555
555 555 5555
5555555555
1 555 555 5555`
.replace(/5/g, '\\d')
.replace(/\(/, '\\(')
.replace(/\)/, '\\)')
.split('\n').join('|')
)
console.log(regex.test('1 456 789 4444'))
1赞
AlgorithmAlchemist
10/4/2023
#2
我会为您推荐 regex101 工具:
function telephoneCheck(str) {
const pattern = /^(1\s?)?(\(\d{3}\)|\d{3})([\s\-]?)\d{3}([\s\-]?)\d{4}$/;
return pattern.test(str);
}
console.log(telephoneCheck("1 456 789 4444")); // true
评论
||
|
||