Reputation: 29
I'm trying to convert the first letter of each word into upper case, as example: "hello world" should be "Hello World".
This is my code so far.
function test() {
var doc = document.getElementById("testInput").value;
var str = doc.replace(/\w\S*/g, doc.charAt(0).toUpperCase() + doc.substring(1).toLowerCase());
document.getElementById("tst").innerHTML = str;
}
And let's say my input is "hello world", the expected outcome is "Hello World" but what I get is "Hello world Hello world".
So my problem is that it only assign the first word and skip the second, but it prints the sentence twice.
Upvotes: 1
Views: 940
Reputation: 1
function capitaizeFirstLetterOfEachWord(str) {
str = str.split(' ')
for (var i = 0; i < str.length; i++) {
str[i] = str[i][0].toUpperCase() + str[i].substr(1)
}
return str.join(' ')
}
console.log(capitaizeFirstLetterOfEachWord("hello hii how are you"))
Upvotes: 0
Reputation: 3435
You can use this:
function Capitalize(str){
var arr = str.split(" ");
for(var i = 0; i< arr.length; i++)
{
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
}
var result = arr.join(" ");
console.log(result);
}
Capitalize("hello world");
And do you know you can do this only by CSS?
div:hover{
text-transform: capitalize;
}
<div>
hover on me!
</div>
Upvotes: 0
Reputation: 9549
Try using:
str.split(" ").map(e => e[0].toUpperCase() + e.slice(1)).join(" ")
Upvotes: 1
Reputation: 44086
Use replace
,charAt(0).toUpperCase()
for first letter and substr(1).toLowerCase()
for the rest of the word. Do this on input
or change
event. If you want to do it like the way you got it don't use innerHTML
, use textContent
instead.
SNIPPET
var inp1 = document.getElementById('input1');
inp1.addEventListener('input', function(e) {
var inp2 = document.getElementById('input2');
var text = this.value;
var res = titleCase(text);
inp2.value = res;
}, false);
function titleCase(str) {
return str.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
<input id='input1'>
<input id='input2'>
Upvotes: 0
Reputation: 2029
You are essentially duplicating the values with your concatenations.
By doing the following you will only be passing in the sub-string's that match the regex pattern to then be replaced:
function test() {
var doc = document.getElementById("testInput").value;
var str = doc.replace(/\w\S*/g, function(txt){ return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
document.getElementById("tst").innerHTML = str;
}
Upvotes: 2
Reputation: 13354
String.prototype.toUpperCaseWords = function () {
return this.replace(/\w+/g, function(a){
return a.charAt(0).toUpperCase() + a.slice(1).toLowerCase()
})
}
Usage:
var stringVariable = "First put into a var";
stringVariable.toUpperCaseWords(); // Output: First Put Into A Var
Source: https://blog.smalldo.gs/2014/06/easily-add-phps-ucwords-ucfirst-to-javascript/
Upvotes: 0