JavaScript符串中每个单词的首字母大写化
map() + replace()
function titleCase(str) { var convertToArray = str.toLowerCase().split(" "); var result = convertToArray.map(function(val){ return val.replace(val.charAt(0), val.charAt(0).toUpperCase()); }); return result.join(" "); } titleCase("hello world"); //"Hello World"
for ··· in + replace()
function titleCase(str) { str = str.toLowerCase().split(' '); for (var i in str) { str[i] = str[i].replace(str[i].charAt(0), str[i].charAt(0).toUpperCase()); }; return str.join(' '); } titleCase("hello world"); //"Hello World"
map() + slice()
function titleCase(str) {
return str.toLowerCase().split(' ').map(function(word) {
return (word.charAt(0).toUpperCase() + word.slice(1));
}).join(' ');
}
titleCase("hello world"); //"Hello World"