2

I am trying to make a function that takes a string and return a string with all the first latters of a word in uppercase and the rest in lowercase.

Here is what I have:

function titleCase(str) {
  str.toLowerCase();
  var strAr = str.split(" ");
  for (var i = 0; i < strAr.length; i++) {
    strAr[i].charAt(0).toUpperCase();
  }
  str = strAr.join(" ");
  return str;
}

titleCase("I'm a little tea pot");

For example, it should change 'My name is nikos' into 'My Name Is Nikos'

Why is the code above not working?

AncientSwordRage
  • 6,865
  • 14
  • 82
  • 158
Xrs
  • 31
  • 1
  • 5
  • 2
    `str.toLowerCase()` and `strAr[i].charAt(0).toUpperCase()` do nothing. You have to save the result of them somewhere. – Sebastian Simon Nov 17 '15 at 21:08
  • Possible duplicate of [Convert string to title case with JavaScript](https://stackoverflow.com/questions/196972/convert-string-to-title-case-with-javascript) – Jannie Theunissen May 24 '19 at 07:12

6 Answers6

3

In your for loop you need to assign a value in your loop, like this:

strAr[i] = strAr[i].charAt(0).toUpperCase();

Another (slightly more organized) way to do this: we will make a function to take a word and capitalize it, then we will make a function that takes a string, splits it on a space, capitalizes each word and rejoins and returns the string. Use it on your own string with titleCase('hi there')

function capitalize(str) {
  if(str.length == 0) return str;
  return str[0].toUpperCase() + str.substr(1);
}

function titleCase(str) {
  return str.split(' ').map(capitalize).join(' ');
}
David Zorychta
  • 12,403
  • 5
  • 42
  • 75
2

You will need to do an assignment for your string, so the first capital letter then the rest of the string as a lowercase:

strAr[i] = strAr[i].charAt(0).toUpperCase() + strAr[i].substring(1).toLowerCase();   

Note the value strAr[i].charAt(0).toUpperCase() will only return the first character as a capital letter, it will not actually change the string in any way.

Here is a simple example

Spencer Wieczorek
  • 20,481
  • 7
  • 40
  • 51
  • 2
    This is the only correct answer because it is the only answer that answered the question "I can't understand why the code above is not working" Everyone else just gave a different solution. – AtheistP3ace Nov 17 '15 at 21:11
  • 1
    @AtheistP3ace Thanks, I actually didn't notice that the rest of the items need to be converted to lower-case (*if not so already*), fixed. So now it's a correct answer :) – Spencer Wieczorek Nov 17 '15 at 21:21
2

Extends the String class:

Replace every word with a toUpperCase'd version of itself.

String.prototype.capitalize = function() {
    return this.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
};


console.log("jose maria gonzales".capitalize()); 
// Jose Maria Gonzales
Oliver Zeyen
  • 723
  • 5
  • 7
  • Note, for future stackizens viewing this code, add anything to `prototype` is largely discouraged: https://stackoverflow.com/q/11904203/1075247 – AncientSwordRage Nov 30 '21 at 17:25
2

It's not working because you still need to assign the result of strAr[i].charAt(0).toUpperCase():

strAr[i] = strAr[i].charAt(0).toUpperCase() + strAr[i].slice(1);

It's worth pointing out that the .toUpperCase()/.toLowerCase() methods do not mutate/alter the value of the string (which is why you need to assign it). You can simplify your code to the following:

Example Here

function titleCase(str) {
    var strAr = str.toLowerCase().split(' ');
    for (var i = 0; i < strAr.length; i++) {
        strAr[i] = strAr[i].charAt(0).toUpperCase() + strAr[i].slice(1);
    }
    return strAr.join(' ');
}

console.log(titleCase('This is a simple test.'));
// This Is A Simple Test.

As an alternative to what you wrote, you could also use the following:

Example Here

function titleCase (str) {
  return str.toLowerCase().replace(/(^|\s)(\w)/g, function(x) {
    return x.toUpperCase();
  });
}

console.log(titleCase('This is a simple test.'));
// This Is A Simple Test.

It will convert the entire input string to lower case, and then capitalize all characters succeeding whitespace (based on the match).

Josh Crozier
  • 219,308
  • 53
  • 366
  • 287
0

use below code for ucword

        function titleCase(str) {
            return (str + '')
                .replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function($1) {
                    return $1.toUpperCase();
                });
        }

        var data = titleCase("I'm a little tea pot");
        document.write(data);
Mogsdad
  • 42,835
  • 20
  • 145
  • 262
Chetan Ameta
  • 7,506
  • 3
  • 29
  • 44
0
function titleCase(str) {
  str = str.split(' ');
  var title ="";
  var result = [];
  for(var i = 0; i < str.length; i++){
    title = str[i].toLowerCase();
    result.push(title[0].toUpperCase()+title.slice(1));
  }
  return result.join(' ');
}
console.log(titleCase('This is a simple test.'));
// This Is A Simple Test.

really easy to understand and follow through...

Emmanuel Ndukwe
  • 307
  • 5
  • 6
  • 1
    Please provide an explanation of why this is the correct way to solve the problem in addition to the code above. Check out [How to Answer](https://stackoverflow.com/help/how-to-answer) for more details on providing good answers. – Tim Hutchison Jun 01 '17 at 12:44