Abdelilah Zaidane
Abdelilah Zaidane

Reputation: 87

How to convert a string to to Title Case in Javascript?

I want a function that capitalizes the first letter of each word in a string in pure Javascript.

For example:

console.log(titleCase("I'm a little teapot"));
//I'm A Little Teapot

The function can't use .split or .map.

Here is what I tried:

function titleCase(str) {
    str.toLowerCase();
    var string="";
    for(var i=0 ;i<str.length;i++){
        if(i===0){
            str[0].toUpperCase();
            string+=str[0];
        } else if(str[i]===" "){
            str[i+1].toUpperCase();
            string+=str[i]+str[i+1];
        }
        string+=str[i]; 
    }
    return  string;
}

Upvotes: 1

Views: 134

Answers (5)

Lord Elrond
Lord Elrond

Reputation: 15992

This is quite verbose, but, alas, titleCase without any "methods":

var charDict = {'a':'A', 'b':'B', 'c':'C', ...};

function titleCase(str){
    var i = 0;
    var result = '';

    while (str[i]) {
        var char = str[i];
        if (((i === 0) || (str[i-1] === ' ')) && (char in charDict)) {
          result += charDict[char];
        }
        else {
          result += char;
        }
        i++;
    }
    return result;
}

Note that you will have to add every character to charDict for this to actually work.

I'd strongly discourage using this in production code. Instead I would use Aaron's first answer.

Upvotes: 2

user9683096
user9683096

Reputation:

Another possibility is by using ASCII:

public String upperCase(String words) {
 String res = "";
 for (int i = 0; i < words.length(); i++) {
  int ascii = (int) words.charAt(i);
  if (ascii > 96 && ascii < 123) {
   res += (char)(ascii - 32);
  } else {
   res += (char) ascii;
  }
 }
 return res;
}

Upvotes: 0

Aaron Plocharczyk
Aaron Plocharczyk

Reputation: 2832

The easiest way is to split the string into an array, map each item in the array into your desired format, and then join the array back into a string again.

function titleCase(str) {
  return str.split(" ").map(word => word.charAt(0).toUpperCase() + word.substring(1)).join(" ");
}

console.log(titleCase("I'm a little teapot"));

But if you don't want to use split or map, you can do this:

function titleCase(str) {
  var newStr = "";
  for (var i = 0; i < str.length; i++) {
    newStr += (i == 0 || str[i - 1] == " ") ? str[i].toUpperCase() : str[i];
  }
  return newStr;
}

console.log(titleCase("I'm a little teapot"));

Upvotes: 1

symlink
symlink

Reputation: 12209

let str = "the quick brown fox jumped over the lazy dog"

let res = str.split(" ").map(word => {
    let arr = word.split("")
    return arr.map((let, idx)  => idx === 0 ? let.toUpperCase() : let).join("")  
}).join(" ")

console.log(res)

Update

Without map() or split():

let str = "the quick brown fox jumped over the lazy dog"

let firstLet = false

for(let i=0; i<str.length; i++){

    if(i==0 || firstLet && str[i] !== " "){
        str = str.substr(0, i) + str[i].toUpperCase() + str.substr(i + 1);
        firstLet = false
    }
    if(str[i] === " "){
        firstLet = true
    }
}

console.log(str)

Upvotes: 0

HARI CHARAN K
HARI CHARAN K

Reputation: 79

This is a slight improvement to the above code in performance with a lesser number of operations and time complexity.

const res = str.split(" ").map(word => 
    `${word.charAt(0).toUpperCase()+word.substr(1)}`
).join(" ")

Upvotes: 0

Related Questions