1

I'm trying to change subindex of string array but it's not modifing.There is the jsbin link.

function LetterCapitalize(str) {
  var arr = str.split(" ");

  var nstr = "";
  for (var i = 0; i < arr.length; i++) {

    var ltr = arr[i][0];
    console.log('ltr: ' + ltr.toUpperCase());
    arr[i][0] = ltr.toUpperCase();
    nstr += arr[i] + " ";
  }
  str = nstr.trim();
  console.log("result: " + str);
  return str;
}

LetterCapitalize("hello world");

1
  • 1
    because strings are immutable. Commented Sep 24, 2016 at 9:43

3 Answers 3

2

You could try something like the following:

function LetterCapitalize(str) { 
    var arr = str.split(" ");

    var nstr = "";
    for(var i=0; i<arr.length; i++){
        arr[i] = arr[i][0].toUpperCase()+arr[i].slice(1);
        nstr+=   arr[i] + " ";
    }

    str = nstr.trim();    

  console.log("result: " + str);

  return str; 

}

console.log(LetterCapitalize("hello world"));

The line that does the difference is the following:

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

What we are doing here is to capitalize the first letter of the string at arr[i] and then concatenate the capitalized letter with the rest letters.

Sign up to request clarification or add additional context in comments.

1 Comment

Instead of concatenate in nstr variable better to use return arr.join(' ');
2

That's because (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Character_access):

For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable.

I.e. strings are immutable.

Comments

2

You could as well just use string.replace matching the first char in each word, using a callback function to upper case the character.

Something like this.

var str = "hello world";

var newStr = str.replace(/\b(\w)/g, function(chr) {
  return chr.toUpperCase()
})

console.log(newStr)

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.