flatbreadcandycane
flatbreadcandycane

Reputation: 365

How do I title case a sentence in javascript using simple substring function?

I'm trying to title case a string which capitalizes only the first character in each word. I tried doing it using the following code. This is what I've done till now.

function titleCase(str) {
 var lowstr = str.toUpperCase();
  var array=lowstr.split(' ');
  var arr;
  var arr1;
   for(var i=0;i<array.length;i++)
    {
      arr1=array[i].substring(0,1); 
      
      for(var j=0;j<array[i].length;j++)
        {
      arr=array[j].substring(1).toLowerCase();
        }
      arr=arr1.concat(arr);     
    }
        array.join(" ");
  return array;
}

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

Upvotes: 1

Views: 436

Answers (5)

Arslan Mujeeb
Arslan Mujeeb

Reputation: 1

Check This Out..

function titleCase(str) {

 var arr=str.split('');
 var array=[];

for(var x=0;x<arr.length;x++)
   { if(x==0){
  array[x]=arr[x].toUpperCase();
  x++;
      }

 array[x]=arr[x].toLowerCase();

  if(arr[x]==' ')
    {
      array[x+1]=arr[x+1].toUpperCase();
      x++;
    }
}
var st=array.join('');
return st;
 }

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

Upvotes: -1

PakiPat
PakiPat

Reputation: 1085

If you're willing to forgo substring and consider a more 'functional' approach, try this.

String.prototype.titleCase = function() {
    t = this.toLower().split(' ').map((word) => word.charAt(0).toUpperCase()+word.slice(1)).join(' ');
    return t;
}

Since I've declared the function on the String.prototype, you can use it thus:

"This is a title".titleCase() // >> "This Is A Title"

which may not be 100% the way newspaper editors would have it, but it does what you seem to want it to do. Let me know if you need an explanation.

Also, if you want a function to use thus: TitleCase("some sentence here") you can easily refactor the code. Let me know if you need further explanation.

Upvotes: 0

Emil S. J&#248;rgensen
Emil S. J&#248;rgensen

Reputation: 6366

Regular expressions solution to the problem:

console.log(
//Base string
"i'm a little tea pot"
//Enforce lowercase
  .toLowerCase()
  //Regular expression replace with uppercase
  .replace(
    /(\s+.)|^\w/ig,
    function(v) {
      return v.toUpperCase();
    })
);

Upvotes: 1

byxor
byxor

Reputation: 6369

It appears as if you're trying to do too much in your titleCase function. I would take a slightly different approach that follows Single Responsibility Principle a little more closely.

I would have...

  1. A function to titleCase a single word.
  2. A function that titleCases each word in a sentence.

Example:

function titleCaseSingleWord(word) {

    if (word.length === 0) {
        return "";
    }

    var result = word[0].toUpperCase();
    for (var i = 1; i < word.length; i++) {
        result += word[i].toLowerCase();
    }

    return result;
}

function titleCaseSentence(sentence) {
    var titleCasedWords = [];

    var words = sentence.split(" ");
    for (var i = 0; i < words.length; i++) {
        var word = words[i];
        var titleCasedWord = titleCaseSingleWord(word);
        titleCasedWords.push(titleCasedWord);
    }

    return titleCasedWords.join(" ");
}

console.log(titleCaseSentence("im a liTTLE teapot"));
// "Im A Little Teapot"

Reasoning Behind Multiple Functions:

  • It makes it easier to test each individual function and find the errors quicker. It also helps to keep your functions shallow.

Notes:

  • These functions are a little bit messy and could do with some refactoring, but I'll leave that to you as a mini exercise.

  • Also, one could go further and say that titleCaseSentence is both splitting the words and titleCasing them, so it should be split up further. That's entirely up to you whether you want to do that or not.

Upvotes: 2

S.V.
S.V.

Reputation: 1221

you set them all to uppercase, then find the letters that are supposed to be lower case.

What I'd do is the opposite. I'd start off the same, with

arr = str.split(" ")

but then you can go

for(var x = 0; x < arr.length; x++)

arr[x].substring(0,1) = arr[x].substring(0,1).toUpperCase()

and then join them back up.

Can't see why you'd need a nested loop for this.

Upvotes: 0

Related Questions