所以我正在研究一个项目,正如标题所述,我正在尝试确定javascript中字符串的第一个字母是否是元音。到目前为止,我的代码看起来像这样。
function startsWithVowel(word){
var vowels = ("aeiouAEIOU");
return word.startswith(vowels);
}
您已经很接近了,只需使用[0]
将单词切成薄片然后检查:
function startsWithVowel(word){
var vowels = ("aeiouAEIOU");
return vowels.indexOf(word[0]) !== -1;
}
console.log("apple ".concat(startsWithVowel("apple") ? "starts with a vowel" : "does not start with a vowel"));
console.log("banana ".concat(startsWithVowel("banana") ? "starts with a vowel" : "does not start with a vowel"));
startsWith
仅接受一个字符。对于这种功能,请改用正则表达式。从单词(word[0]
)中获取第一个字符,然后查看其字符是否包含在不区分大小写的字符集中,[aeiou]
:
function startsWithVowel(word){
return /[aeiou]/i.test(word[0]);
}
function startsWithVowel(word){
return /[aeiou]/i.test(word[0]);
}
console.log(
startsWithVowel('foo'),
startsWithVowel('oo'),
startsWithVowel('bar'),
startsWithVowel('BAR'),
startsWithVowel('AR')
);
ES6 oneliner:
const startsWithVowel = word => /[aeiou]/i.test(word[0].toLowerCase());
如果您不在乎重音符号,此方法将起作用:
const is_vowel = chr => (/[aeiou]/i).test(chr);
is_vowel('e');
//=> true
is_vowel('x');
//=> false
但是它会失败,并且带有法语中常见的重音符号:
is_vowel('é'); //=> false
您可以使用String#normalize
来“分割”一个字符:基本字符后跟重音符号。
String#normalize
现在您可以摆脱重音符号:
'é'.length;
//=> 1
'é'.normalize('NFD').length;
//=> 2
'é'.normalize('NFD').split('');
//=> ["e", "́"] (the letter e followed by an accent)
贷项const is_vowel = chr => (/[aeiou]/i).test(chr.normalize('NFD').split('')[0]);
is_vowel('é');
//=> true
至this fantastic answer