试图编写代码以查找字符串的第一个字母是否是javascript中的元音

问题描述 投票:1回答:4

所以我正在研究一个项目,正如标题所述,我正在尝试确定javascript中字符串的第一个字母是否是元音。到目前为止,我的代码看起来像这样。

function startsWithVowel(word){
   var vowels = ("aeiouAEIOU"); 
    return word.startswith(vowels);
}
javascript
4个回答
2
投票

您已经很接近了,只需使用[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"));

1
投票

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

1
投票

ES6 oneliner:

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

0
投票

如果您不在乎重音符号,此方法将起作用:

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

© www.soinside.com 2019 - 2024. All rights reserved.