-2

I created this code and most of it is working with the exception of the toUpperCase which should make every first letter of a word uppercase. There is no error so I am not sure why the method is not currently working. Why may this be the case.

let str ="insert string here"
String.prototype.toCase = function () {
  let arrayWord = str.split("");
  for (let i = 0; i<str.length; i++){
    if (arrayWord[i]===" "){
      arrayWord[i+1].toUpperCase();
    }
    else{
    }
  }
  let result = arrayWord.join("");
  return (result)
};
sacora
  • 265
  • 1
  • 3
  • 8

4 Answers4

3

toUpperCase returns the modified string, it doesn't modify the string it's called from.

var a = "donald";
var b = a.toUpperCase();

console.log(a) // donald
console.log(b) // DONALD

Here i made it work keeping your code structure, but it still has some issues. If you want later i'll type a solution which takes into account all corner cases.

var str = "donald fauntleroy duck"

var str_array = str.split("");
var ret_str = ""
for(var i=0; i<str_array.length; i++)
    {
    if(i > 0)
        {//avoid checking out of scope
        if(str_array[i-1] === " ")
            {
            ret_str += str_array[i].toUpperCase();
            }
        else
            {
            ret_str += str_array[i];
            }
        }
    }

return(ret_str);
Barnack
  • 921
  • 1
  • 8
  • 20
1

You forgot to assign the result of String#toUpperCase as it's returning a modified string rather than working on the called string.

...returns the calling string value converted to uppercase...

Add a assignment like: arrayWord[i + 1] = arrayWord[i + 1].toUpperCase();

Demo

let str ="insert string here"
String.prototype.toCase = function () {
  let arrayWord = str.split("");
  for (let i = 0; i < str.length; i++){
    if (arrayWord[i] === " "){
      arrayWord[i + 1] = arrayWord[i + 1].toUpperCase();
    }
    else{
    }
  }
  let result = arrayWord.join("");
  return (result)
};

console.log(str.toCase());
Kristianmitk
  • 4,528
  • 5
  • 26
  • 46
0

Set new value arrayWord[i+1]=arrayWord[i+1].toUpperCase();

Whome
  • 10,181
  • 6
  • 53
  • 65
0

This function make the first letter of words uppercase:

function uppercaseFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

var output = "";

let str ="insert string here";

str = str.split(' ').forEach(itm => output += uppercaseFirstLetter(itm) + ' ');

console.log(output);
Saeed
  • 5,413
  • 3
  • 26
  • 40