4

I am working through some problems on CoderByte. The goal of this function is to take a string and capitalize the first letter of each word. For example, 'hello world' to 'Hello World'. I can't figure out why this code gives me 'hello world' and not 'Hello World'. I know this line array[i][0] = array[i][0].toUpperCase(); is the problem, but don't understand why it isn't working. I came up with an alternative solution but I am wondering why this didn't work. Thanks so much 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');
3

6 Answers 6

2

The issue is that array[i] refers to a string. However, strings are immutable in JavaScript, so this operation fails: array[i][0] = array[i][0].toUpperCase(). You cannot set individual indices on a string.

To accomplish what you want, you will have to create a new string with the first letter capitalized. Here's one way to do it, borrowing from another 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');
Sign up to request clarification or add additional context in comments.

1 Comment

Ah ok I didn't realize that. Thank you very much for your help
1

You can just use regular expressions for this case:

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

Comments

1

An effective way to deal with this would be using the .map() function

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

And a step by step guide to the code:

.split(" ") makes an array by adding a new item every time there is a space

.map() takes a value, plugs it into a function, and modifies the result based on what the function returns.

.charAt(0) gets the first letter and .toUpperCase() capitalizes it

.slice(1) Gets every letter after the first letter.

Cheers, TheGenieOfTruth

(Done on mobile, so formatting is spotty and code is untested)

Comments

0

A go at a functional approach:

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 accounts for \n (newline) and \t (tab) characters as capital letter boundaries.

Comments

0

You did not create a two-dimensional array. Can't use the [0] reference -- have to use substrings.

Note the difference between substr (where the second parameter is a length -- we want only 1 character), and substring (where the second parameter is the ending position - omitted here so goes to end of string).

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

1 Comment

Correct. However, better to also provide an example, as "have to use substrings" is a broad statement that the OP may not understand.
-1

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.