0

I want to change to make the first letters of the words in the string uppercase, and after translating into an array, I use the map method. The problem is that inheritance does not work in this method, as I understand it, because when you return the map element, the original string is returned:

const str = 'dkdg gkdj wijoerbj'
let r = str.split(' ').map((item, index) => {
    item[0] = item[0].toUpperCase()
    return item
})

unchanged first letters will also be returned with such a code entry(is in the map()):

item[0] = item[0].toUpperCase()
return item[0]

however, when I return the first line, the letters still become uppercase, but I do not know how to return the rest of the word in this case(is in the map()):

return item[0] = item[0].toUpperCase()

why inheritance does not work as it should, tell me, please, and how to add the rest of the word if there are no other options?

rid
  • 61,078
  • 31
  • 152
  • 193
  • 5
    Strings are immutable. `let str = 'abc'; str[1] = 'd'; console.log(str);` does NOT yield `"adc"`. – Niet the Dark Absol May 12 '20 at 17:13
  • An alternative approach to the problem: `let r = str.replace(/\b\w/g,l=>l.toUpperCase());` -- much simpler :) – Niet the Dark Absol May 12 '20 at 17:14
  • 2
    Does this answer your question? [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) – jarmod May 12 '20 at 17:16

3 Answers3

1

You need to cancat the first letter with rest of the string. Also these two lines item[0] = item[0].toUpperCase();return item though will convert the first letter to uppercase but it will still return the original sting because item represent the original word nut not the modified text

const str = 'dkdg gkdj wijoerbj'
let r = str.split(' ').map((item, index) => {

  return item.charAt(0).toUpperCase() + item.substring(1, item.length)
});


console.log(r)
brk
  • 48,835
  • 10
  • 56
  • 78
0

We can do this with two array map methods as bellow.

const str = 'dkdg gkdj wijoerbj';

let r = str.split(' ').map((item, index) => {
    return ([...item].map((letter, i) => {
        return (i == 0) ? letter.toUpperCase() : letter;
    })).join('');
});


console.log(r);
0

const str = 'dkdg gkdj wijoerbj'
let r = str.split(' ').map(x=> x[0].toLocaleUpperCase());
console.log(r)

u can try this code to get first letters of the words in the string uppercase into new arry using map and returns capital letter of each first letter

Mo Salah
  • 11
  • 4