代码有效,但我需要一种优化的方式,在JavaScript中,我可以得到一些关于此的建议!
//capitalize vowels in a string
(function (string) {
var str = string.split("");
console.log(str);
var name = [];
for (var i = 0; i < str.length; i++) {
//console.log(str[i]);
if (str[i] == "a") {
str[i] = "A";
}
if (str[i] == "e") {
str[i] = "E";
}
if (str[i] == "i") {
str[i] = "I";
}
if (str[i] == "o") {
str[i] = "O";
}
if (str[i] == "u") {
str[i] = "U";
}
}
console.log(str);
return str; })("Hello Jane")
答案 0 :(得分:1)
怎么样?
var result = (function(string) {
return string.replace(/[aeiou]/g, function(char) {
return char.toUpperCase();
});
})("Hello Jane")
console.log(result)
&#13;
没有匿名功能
var string = "Hello Jane";
var result = string.replace(/[aeiou]/g, function (char) {
return char.toUpperCase();
});
console.log(result)
演示:Fiddle
不使用正则表达式
var map = {
a: 'A',
e: 'E',
i: 'I',
o: 'O',
u: 'U'
}
var string = "Hello Jane";
var result = string.split('').map(function(char, i) {
return map[char] || char;
}).join('');
console.log(result)
&#13;