简体   繁体   中英

Capital letters in a string using the 'map' method

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?

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)

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);

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM