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
  • 7,086
  • 19
  • 90
  • 173
Xrs
  • 31
  • 1
  • 5

7 Answers7

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
  • 13,039
  • 6
  • 45
  • 81
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
  • 21,229
  • 7
  • 44
  • 54
  • 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
  • 783
  • 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
  • 233,099
  • 56
  • 391
  • 304
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
  • 44,709
  • 21
  • 151
  • 275
Chetan Ameta
  • 7,696
  • 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
  • 326
  • 5
  • 7
  • 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
0

A simple ready-to-use JS function for Title case

function toTitleCase(txt = ''){
    if (txt && txt.length > 0) {
      const txtInLC = txt.toLowerCase();
      txt = txtInLC.substring(0,0) + txtInLC[0].toUpperCase() + txtInLC.substring(1);
    }
    return txt;
  };

toTitleCase('HELLO WORLD')

Some use-cases
input output
'hello world' 'Hello world'
'Hello World' 'Hello world'
'HELLO World' 'Hello world'
'hello WORLD' 'Hello world'
'HELLO WORLD' 'Hello world'
Omal Perera
  • 2,971
  • 3
  • 21
  • 26