Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lowercase all letters in a string except the first letter and capitalize first letter of a string? - JavaScript

I.e., if I have an input string:

input = 'hello World, whatS up?'

I want an output string to be:

desiredOutput = 'Hello World, whats up?'

If the first letter of any word in the string is already in upper case, leave it as is.

like image 371
jasan Avatar asked Oct 22 '16 18:10

jasan


People also ask

How do you make a string lowercase except the first letter?

The toLowerCase method converts a string to lowercase letters. The toLowerCase() method doesn't take in any parameters. Strings in JavaScript are immutable. The toLowerCase() method converts the string specified into a new one that consists of only lowercase letters and returns that value.

How do you change all caps to lowercase except first letter in Java?

toLowerCase(); Here substring(0,1). toUpperCase() convert first letter capital and substring(1). toLowercase() convert all remaining letter into a small case.

Which method is used to lowercase all the characters in a string in JavaScript?

The toLowerCase() method returns the value of the string converted to lower case. toLowerCase() does not affect the value of the string str itself.

How do you capitalize the first letter of a string in TypeScript?

To capitalize the first letter of a string in TypeScript: Call the toUpperCase() method on the letter.


Video Answer


1 Answers

const upperCaseFirstLetter = string =>
 `${string.slice(0, 1).toUpperCase()}${string.slice(1)}`;

const lowerCaseAllWordsExceptFirstLetters = string =>
 string.replaceAll(/\S*/g, word =>
  `${word.slice(0, 1)}${word.slice(1).toLowerCase()}`
 );

const input = 'hello World, whatS up?';
const desiredOutput = upperCaseFirstLetter(lowerCaseAllWordsExceptFirstLetters(input));

console.log(desiredOutput);

Based on:

How do I make the first letter of a string uppercase in JavaScript?

and

How to capitalize first letter of each word, like a 2-word city?

like image 95
Krzysztof Dąbrowski Avatar answered Oct 19 '22 00:10

Krzysztof Dąbrowski