Wrap the first letter of each word in a string using JavaScript

I'm currently trying to figure out how to use the first letter of each word in a string (all other letters in a word are lowercase). For example: "Coding may be confusing"

Here is what I still have. I know that I clearly have no code, I just do not know what should happen next. I am also not sure that what I have is even right. Any help would be greatly appreciated.

function titleCase(str) {
  var words = str.toLowerCase.split(' ');

  for(i = 0; i < words.length; i++) {
    var firstLetter = words[i].charAt(0).toUpperCase;
  }

  return words.join(' ');
}

titleCase("I'm a little tea pot");
+4
source share
4 answers

You can use and and do something like that map() substring()

function titleCase(str) {
  return str.toLowerCase().split(' ').map(function(v) {
    return v.substring(0, 1).toUpperCase() + v.substring(1)
  }).join(' ');
}
document.write(titleCase("I'm a little tea pot"));
Run codeHide result
+3
source

Try this code:

var str = "this is sample text";
console.log(toTitleCase(str));

function toTitleCase(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

Jsfiddle

+2
source

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);
    
Hide result
0

var text = "I'm a little tea pot"

text = text.split(" ")
//["I'm", "a", "little", "tea", "pot"]

final = $.map(text, function(val,i){
 return val = val[0].toUpperCase() + val.slice(1,val.length)
})
// ["I'm", "A", "Little", "Tea", "Pot"]

final.join(" ")
// "I'm A Little Tea Pot"

,

function titleCase(str) {
    return text.split(" ").map(function(val,i){
        return val[0].toUpperCase() + val.slice(1,val.length)
    }).join(" ")
}

var text = "I'm a little tea pot"
console.log(titleCase(text))
//"I'm A Little Tea Pot"
0

Source: https://habr.com/ru/post/1617000/


All Articles