罗伊想提高自己的编程比赛打字速度。他的朋友建议他反复输入句子“快速的棕色狐狸跳过懒狗”。该句子被称为pangram,因为它包含字母表中的每个字母。
在多次输入句子后,Roy厌倦了它,因此他开始寻找其他的人物。
给定一个句子,请确定它是否是Pangram。忽略大小写。
如果输入字符串是Pangram,则应返回字符串pangram。否则,它不应返回pangram。
样本输入
我们迅速判定古董象牙带扣获得下一个奖项
// pangram
我们迅速判断了古董象牙带扣的价格
//不是pangram(缺少字母x)
码
function pangrams(s) {
const exp = /[a-z]/gi;
if (s.includes(exp)) {
return 'pangram';
} else {
return 'not pangram';
}
}
TypeError:String.prototype.includes的第一个参数不能为正则表达式
题
如果我正确解决了问题,如何在仍能使用正则表达式的情况下解决此问题?
您的正则表达式是错误的。它只会检查字符串是否包含从到的一个字母。您还没有正确测试它-检查子字符串是否包含在较大的字符串中,而不是用于正则表达式验证。a
z
String.prototype.includes
如果要测试正则表达式是否与字符串匹配,请使用.test
。要检查带有正则表达式的字符串中是否所有字母都存在,您必须(?=.*a)
对每个字符重复,例如:
const pattern = /^(?=.*a)(?=.*b)(?=.*c)(?=.*d)(?=.*e)...../i;
return s.test(pattern);
但这确实很丑陋且重复。
我不认为正则表达式是解决问题的方法。考虑遍历字符代码以将字符从A转换为Z,并.includes
改为使用:
const test = (str) => {
const strUpper = str.toUpperCase();
// start at A
for (let i = 65; i <= 90; i++) {
if (!strUpper.includes(String.fromCharCode(i))) {
return false;
}
}
return true;
};
console.log(test('The quick brown fox jumps over the lazy dog'));
console.log(test('The quick brown fox jumps over the lazy do'));
如果必须使用正则表达式,则可以通过遍历所有字符代码来动态构造它:
const test = (str) => {
const pattern = new RegExp(
'^' +
Array.from(
{ length: 26 },
(_, i) => `(?=.*${String.fromCharCode(i + 65)})`
).join(''),
'i'
);
return pattern.test(str);
};
console.log(test('The quick brown fox jumps over the lazy dog'));
console.log(test('The quick brown fox jumps over the lazy do'));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句