如何在JavaScript中查找字符串的第一个字母是否为元音字母

3

我正在进行一个项目,如题所述,我正在尝试查找JavaScript中字符串的第一个字母是否为元音字母。到目前为止,我的代码看起来像这样:

function startsWithVowel(word){
    var vowels = ("aeiouAEIOU"); 
    return word.startswith(vowels);
}

@AndrewL64 不同的语言,但逻辑仍然适用。 - A.J. Uppal
@A.J.Uppal,我已经撤回了关闭投票。感谢您的提醒。 - AndrewL64
这个回答解决了你的问题吗?检查一个单词是否以元音字母开头? - undefined
4个回答

4

你已经接近答案了,只需要使用[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"));


3

如果您不在意重音符号,以下做法可行:

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

感谢这篇优秀答案,关于这个问题


2

ES6一行代码:

const startsWithVowel = word => /[aeiou]/i.test(word[0]);

虽然您的方法很漂亮,但是(仅用于测试目的)如果提供的索引超过字符串长度。它对他们说是正确的。vowels.indexOf(word [0])非常适合这个目的。 - Bangash
你能提供更多关于这个一行函数的细节吗?在我的情况下,这个代码不起作用: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. Dunon

2

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')
);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接