return count
for
循環,或使用RegExp
/[^aeiou]/ig
作爲第一個參數.replace()
與""
作爲字符串替換,獲取字符串.legnth
通過.replace()
vowelLength = "aide".replace(/[^aeiou]/ig, "").length;
console.log(vowelLength);
vowelLength = "gggg".replace(/[^aeiou]/ig, "").length;
console.log(vowelLength);
返回
RegExp
描述
字符集
[^xyz]
甲否定或補充的字符集。也就是說,它匹配括號內未包含的任何內容。
標誌
i
忽略大小寫
g
全局匹配;找到所有的比賽,而不是第一場比賽
後停止使用傳播元素,Array.prototype.reduce()
,String.prototype.indexOf()
或String.prototype.contains()
如果支持
const v = "aeiouAEIOU";
var vowelLength = [..."aide"].reduce((n, c) => v.indexOf(c) > -1 ? ++n : n, 0);
console.log(vowelLength);
var vowelLength = [..."gggg"].reduce((n, c) => v.indexOf(c) > -1 ? ++n : n, 0);
console.log(vowelLength);
或者,而不是創建一個新字符串或新陣列獲得字符串的0財產或迭代字符,你可以使用for..of
循環,RegExp.prototype.test
與RegExp
/[aeiou]/i
遞增初始設置爲0
如果.test()
評估爲true
對傳入的字符變量。
var [re, vowelLength] = [/[aeiou]/i, 0];
for (let c of "aide") re.test(c) && ++vowelLength;
console.log(vowelLength);
vowelLength = 0;
for (let c of "gggg") re.test(c) && ++vowelLength;
console.log(vowelLength);
'返回計數;'搬出到用於環路 –
嘗試'string.match(/ [AEIOU] /克).length' – Rajesh
@Rajesh我最好使用'/ [AEIOU ]/ig' – Phil