admin管理员组

文章数量:1279042

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?

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?

Share Improve this question edited Nov 30, 2021 at 17:23 AncientSwordRage 7,64521 gold badges99 silver badges192 bronze badges asked Nov 17, 2015 at 21:05 XrsXrs 311 silver badge5 bronze badges 3
  • 2 str.toLowerCase() and strAr[i].charAt(0).toUpperCase() do nothing. You have to save the result of them somewhere. – Sebastian Simon Commented Nov 17, 2015 at 21:08
  • Possible duplicate of Convert string to title case with JavaScript – Jannie Theunissen Commented May 24, 2019 at 7:12
  • FYI, this isn't title case. Titles don't have every word capitalized. – isherwood Commented Nov 2, 2022 at 19:51
Add a ment  | 

7 Answers 7

Reset to default 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(' ');
}

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).

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

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

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);
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...

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'

本文标签: stringJavaScript titleCase function without regexStack Overflow