patternjavascriptMinor
Title case a sentence function
Viewed 0 times
titlecasefunctionsentence
Problem
I am new to programming. I have written a solution in two different ways, but would like to know what is considered a better solution, and why.
Additionally, in terms of performance, why would one be considered better?
Solution 1:
Solution 2:
Additionally, in terms of performance, why would one be considered better?
Solution 1:
function titleCase(str) {
str = str.toLowerCase();
str = str.split("");
str[0] = str[0].toUpperCase();
for(i = 1; i<str.length; i++){
if(str[i+1] == " "){
str[i+2] = str[i+2].toUpperCase();
}
}
str = str.join("");
return str;
}Solution 2:
function titleCase(str) {
str = str.toLowerCase();
str = str.split(" ");
str = str.map(function(val){
val = val.charAt(0).toUpperCase() + val.slice(1);
return val;
});
str = str.join(" ");
return str;
}Solution
A regular expression is really all you need:
Then use the
If you really feel like it, jsperf.com can give you a good idea what the performance is.
/(^| +)([a-zA-Z])/gThen use the
String#replace method and pass in a function:function toTitleCase(s) {
return s.toLowerCase().replace(toTitleCase.WORD_PATTERN, function(match, $1, $2) {
return $1 + $2.toUpperCase();
});
}
toTitleCase.WORD_PATTERN = /(^| +)([a-zA-Z])/g;If you really feel like it, jsperf.com can give you a good idea what the performance is.
Code Snippets
/(^| +)([a-zA-Z])/gfunction toTitleCase(s) {
return s.toLowerCase().replace(toTitleCase.WORD_PATTERN, function(match, $1, $2) {
return $1 + $2.toUpperCase();
});
}
toTitleCase.WORD_PATTERN = /(^| +)([a-zA-Z])/g;Context
StackExchange Code Review Q#113497, answer score: 8
Revisions (0)
No revisions yet.