I am doing a simple function. To turn all words first-letter to upper case, but It simply doesn't work, neither display any errors:
function formatTitle(input) {
var words = input.split(' ');
for (var i = 0; i < words.length; i++) {
words[i][0] = words[i][0].toUpperCase();
};
return words.join(' ');
};
var newTitle = formatTitle("all words first-letter should be upper case");
document.write(newTitle);
I am doing a simple function. To turn all words first-letter to upper case, but It simply doesn't work, neither display any errors:
function formatTitle(input) {
var words = input.split(' ');
for (var i = 0; i < words.length; i++) {
words[i][0] = words[i][0].toUpperCase();
};
return words.join(' ');
};
var newTitle = formatTitle("all words first-letter should be upper case");
document.write(newTitle);
Thanks in advance.
Share Improve this question edited Jul 23, 2015 at 12:42 Tushar 87.2k21 gold badges163 silver badges181 bronze badges asked Jul 23, 2015 at 12:36 user4227915user4227915 2-
Fancy ES6 approach:
[...words[i]].map((a,b)=>!b?a.toUpperCase():a).join('');
. – Sebastian Simon Commented Jul 23, 2015 at 13:39 - @Xufox The fancy ES6 approach is much heavier than a fancy regex approach – Denys Séguret Commented Jul 23, 2015 at 15:30
3 Answers
Reset to default 9The problem is that strings in javascript are immutable. You can't just change a char like this.
A solution would be this:
words[i] = words[i][0].toUpperCase()+words[i].slice(1);
But you could have a simpler and faster code using a regular expression:
return input.replace(/\b\w/g,function(b){ return b.toUpperCase() })
(here with a more plete uppercasing, not just after spaces - if you want to stick to spaces use replace(/(\s+|^)\w/g,function(b){ return b.toUpperCase() })
)
Problem
Because
words[i][0] = 'something'
does not update the words[i]
.
Problem Demo
var myVar = 'abc';
myVar[0] = 'd';
document.write(myVar); // abc
Solution
You can use substr
to get the first character and update the value of whole string.
Solution Demo
function formatTitle(input) {
var words = input.split(' ');
for (var i = 0; i < words.length; i++) {
words[i] = words[i].substr(0, 1).toUpperCase() + words[i].substr(1);
}
return words.join(' ');
}
var newTitle = formatTitle("all words first-letter should be upper case");
document.write(newTitle);
How wrote Denis the reason is that strings in javascript are immutable (numbers and booleans are also immutable).
Another very simple solution for Upperize the first char of a string is:
function firstUpper(word) {
return word.charAt(0).toUpperCase() + word.substring(1);
};
I suggest also to read this post: Understanding Javascript immutable variable
Hope this help