15

I am trying to capitalize the first letter of only the first word in a sentence.

This is the data in the tsx file { this.text({ id: downloadPriceHistory, defaultMessage: 'Download Price History' }) } the id shown above comes from the database where it could be send to the api in various forms.

I have tried to use this logic below:

export function titleCase(string) {
    string = 'hello World';
    const sentence = string.toLowerCase().split('');
      for (let i = 0; i < sentence.length; i++) {
          sentence[i] = sentence[i][0].toUpperCase() + sentence[i];
    }
     return sentence;

}

For example, for the input "Download Price History", the result should be "Download price history".

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Shallesse
  • 189
  • 1
  • 1
  • 6

8 Answers8

33

You only need to capitalize the first letter and concatenate that to the rest of the string converted to lowercase.

function titleCase(string){
  return string[0].toUpperCase() + string.slice(1).toLowerCase();
}
console.log(titleCase('Download Price History'));

This can also be accomplished with CSS by setting text-transform to lowercase for the entire element and using the ::first-letter pseudo element to set the text-transform to uppercase.

.capitalize-first {
  text-transform: lowercase;
}
.capitalize-first::first-letter {
  text-transform: uppercase;
}
<p class="capitalize-first">Download Price History</p>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
11

Using CSS:

p {
  text-transform: lowercase;
}
p::first-letter {
  text-transform: uppercase;
}

Using JS:

const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1).toLowerCase();
Constantin
  • 3,655
  • 1
  • 14
  • 23
9

use ES6 template strings feature:

const titleCase = str => `${str[0].toUpperCase()}${str.slice(1).toLowerCase()}`
Reza Mirzapour
  • 390
  • 3
  • 11
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 10 '21 at 19:02
4

try - make the rest of the string in lowercase as well.

export function titleCase(string) {
     return string[0].toUpperCase() + string.substr(1).toLowerCase()
}
Manas
  • 808
  • 1
  • 7
  • 16
4

Why not just lowercase the entire string, and the uppercase just the first letter of the new string?

function titleCase(string) {
    let sentence = string.toLowerCase();
    let titleCaseSentence = sentence.charAt(0).toUpperCase() + sentence.substring(1, sentence.length);
    return titleCaseSentence;
}

(Also, you're erasing your parameter to the function with that first line)

    string = 'hello World';
Dharman
  • 30,962
  • 25
  • 85
  • 135
3

My suggestion is you get the first element of string and put in uppercase and get the rest of string and apply lowercase function.

titleCase(string) {
  return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
Murilo Góes de Almeida
  • 1,588
  • 5
  • 20
  • 42
3

If you want Regex, in one line:

str.replace(/^(\w)(.+)/, (match, p1, p2) => p1.toUpperCase() + p2.toLowerCase())

Explanation

It divides the string in 2 groups, the 1st character (\w) and the remaining characters (.+), and upper case the 1st group and lower case the second.

let str = 'the quick brown FOX'

str = str.replace(/^(\w)(.+)/, (match, p1, p2) => p1.toUpperCase() + p2.toLowerCase())

console.log(str)
João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
0

Great answers were provided already, but I'm just adding a different method using replace in case anyone needs it.

export function titleCase(string) {
string = 'hello World';
const sentence = string.toLowerCase();
let normalCaseString = sentence.replace(sentence[0], sentence[0].toUpperCase();
}
 return normalCaseString;
}

The way this works is we're utilizing the replace() string method to swap the first letter in the sentence variable with an uppercased version of it. The replace method takes two parameters, the first is the section you want to replace, and the second is what you want to replace it with.

Syntax: replace(pattern, replacement)

According to MDN, pattern

Can be a string or an object with a Symbol.replace method — the typical example being a regular expression. Any value that doesn't have the Symbol.replace method will be coerced to a string.

Alvin
  • 920
  • 3
  • 9