Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript titleCase function without regex

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?

like image 720
Xrs Avatar asked Dec 20 '25 17:12

Xrs


1 Answers

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(' ');
}
like image 99
David Zorychta Avatar answered Dec 22 '25 08:12

David Zorychta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!