0

I tried the below code in JavaScript:

console.log(str.toLowerCase().trim().replace(str[0], str[0].toUpperCase()));

Case 1 - str = 'variable':

const str = 'variable';
console.log(str.toLowerCase().trim().replace(str[0], str[0].toUpperCase()));

It gives the expected output which is, 'Variable', i.e, the first letter of the string is in uppercase.

Case 2 - str = 'Variable':

const str = 'Variable';
console.log(str.toLowerCase().trim().replace(str[0], str[0].toUpperCase()));

It gives the a strange output- 'variable'.

I am quite new to JavaScript and am unable to understand what the reason is for this behavior.

const str = 'Variable';
console.log(str.toLowerCase().trim().replace(str[0], str[0].toUpperCase()));
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • The first parameter of `replace()` is basically the search pattern. So by using `str[0]` there you're telling `replace` to replace whatever the first character of the original string is. Unless it's a lowercase character, that won't work. –  Sep 06 '21 at 19:11
  • 1
    Duplicate: [How do I make the first letter of a string uppercase in JavaScript?](https://stackoverflow.com/questions/1026069/how-do-i-make-the-first-letter-of-a-string-uppercase-in-javascript) –  Sep 06 '21 at 19:11
  • @ChrisG The link you provided solves his problem, but he is trying to understand **what is** the reason for this behaviour. – Zakk Sep 06 '21 at 19:22
  • @Zakk True, which is why I explained the reason in my comment above. I guess you're arguing it's not really a dupe of that other question and I might agree if we didn't also have [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) –  Sep 06 '21 at 19:29

1 Answers1

0

str is a constant, and a string (strings are immutable); it is always

const str = 'Variable';

If you take str[0], you get V.

So, .toLowerCase().trim().replace(str[0] will never match if the first character is upper-case, because the upper-case str[0] will not be contained inside the trimmed, lower-cased string.

I'd save the lower-cased version of the string in a variable first, so you can access that string's [0].

const str = 'Variable';
const lower = str.toLowerCase().trim();
console.log(lower.replace(lower[0], lower[0].toUpperCase()));

Or, to be more precise, extract only the first character, upper-case it, and lower-case the rest.

const str = 'Variable';
const result = (
  str[0].toUpperCase() +
  str.slice(1).toLowerCase()
);
console.log(result);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320