Changing string characters in an array - Javascript

I am working on some issues on CoderByte. The purpose of this function is to take a string and smooth out the first letter of each word. For example, from 'hello world'to 'hello world'. I cannot understand why this code gives me 'hello world', not 'hello world'. I know this line array[i][0] = array[i][0].toUpperCase();is a problem, but I don’t understand why it does not work. I came up with an alternative solution, but I wonder why this did not work. Many thanks for your help!

function LetterCapitalize(str) { 
    var array = str.split(' ');
    for (var i = 0; i < array.length; i++) {
        array[i][0] = array[i][0].toUpperCase();
    }
return array.join('');
} 

LetterCapitalize('hello world');
+4
source share
6 answers

, array[i] . , JavaScript, : array[i][0] = array[i][0].toUpperCase(). .

, , . , SO post:

function capitalizeFirstLetter(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

function capitalizeAllWords(str) { 
    var words = str.split(' ');
    return words.map(capitalizeFirstLetter).join(' ');
} 

capitalizeAllWords('hello world');
+2

:

function LetterCapitalize(str) { 
  var regex = /(\b[a-z](?!\s))/g;
  str = str.replace(regex, function(x) {
      return x.toUpperCase();
  });

  console.log(str);
} 

LetterCapitalize('hello world');
+1

.map()

function cap(string){
    return string.split(" ").map(function(word){
        return word.charAt(0).toUpperCase() + word.slice(1)
    }
}

:

.split("") , ,

.map() , , .

.charAt(0) .toUpperCase()

.slice(1) .

Cheers, TheGenieOfTruth

( , , )

+1

. [0] - .

substr ( - - 1 ), ( - , ).

function LetterCapitalize(str) { 
    var array = str.split(' ');
    for (var i = 0; i < array.length; i++) {
        var firstChar = array[i].substr(0,1).toUpperCase();
        if array[i].length == 1
            array[i]=firstChar;
        else
            array[i]=firstChar + array[i].substring(1);
     }
    return array.join(' ');
} 

LetterCapitalize('hello world');
0

A :

var capitalize = function(str) {
  return str.split(/\s+/)
   .map(function(word) { 
      return word.charAt(0).toUpperCase() + word.slice(1);
    })
  .join(' ');
};

As a bonus, this function also takes into account the characters \n(new line) and \t(tab) as the boundaries of capital letters.

0
source

Try the following:

function LetterCapitalize(str) { 
        var array = str.split(' ');
        for (var i = 0; i < array.length; i++) {

            array[i] = array[i][0].toUpperCase()+array[i].slice(1);

        }
    return array.join(' ');
    } 

LetterCapitalize('hello world');
-1
source

Source: https://habr.com/ru/post/1662088/


All Articles