我正在进行一个项目,如题所述,我正在尝试查找JavaScript中字符串的第一个字母是否为元音字母。到目前为止,我的代码看起来像这样:
function startsWithVowel(word){
var vowels = ("aeiouAEIOU");
return word.startswith(vowels);
}
我正在进行一个项目,如题所述,我正在尝试查找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"));
如果您不在意重音符号,以下做法可行:
const is_vowel = chr => (/[aeiou]/i).test(chr);
is_vowel('e');
//=> true
is_vowel('x');
//=> false
但是如果遇到法语中常见的重音符号,它将无法正常工作:
is_vowel('é'); //=> false
您可以使用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
ES6一行代码:
const startsWithVowel = word => /[aeiou]/i.test(word[0]);
set enum(text) { let startsWithVowel = (text) => /[aeiou]/i.indexOf(text[0]); this.title = startsWithVowel ? "Créer un nouvel ${text.slice(0, -1)}" : "Créer un nouveau ${text.slice(0, -1)}" }
- Yohan W. DunonstartsWith
只接受单个字符。对于这种功能,请使用正则表达式。从单词中取出第一个字符 (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')
);