2

I'm trying to capitalize first letter of array with strings, I add my method to String but it's only returning the first letter capitalized not the full sentence. So it should be "Hi There How Are You?"

const str = "Hi there how are you?";

String.prototype.toJadenCase = function(st) {
  let arr = st.split(" ");
  arr.forEach(function(ele, index) {
    arr[index] = ele.charAt(0).toUpperCase();
  });
  return arr;
};

console.log(String.prototype.toJadenCase("Hi there how are you"));

Returns array of only first letter not full word ["H", "T", "H", "A", "Y"]

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
HelloWorld
  • 105
  • 1
  • 8
  • You have to change `arr[index][0] = ele.charAt(0).toUpperCase();` Currently you are replacing the whole string at `index` position in the array. Rather only replace the first letter – Panther Jun 22 '19 at 02:45
  • look at https://stackoverflow.com/questions/1026069/how-do-i-make-the-first-letter-of-a-string-uppercase-in-javascript – Rodrigo Porcionato Jun 22 '19 at 02:49
  • This can also be donde using `string.replace()`. Something like this: `const toJadenCase = (str) => str.replace(/\s./g, m => m.toUpperCase())` – Shidersz Jun 22 '19 at 03:03

1 Answers1

2

You need to add remaining part of string as well

const str = "Hi there how are you?";

String.prototype.toJadenCase = function (st) {
    let arr = st.split(" ");
    arr.forEach(function(ele, index) {
        arr[index] = ele.charAt(0).toUpperCase() + ele.substr(1)
    });
    return arr;
};

console.log(String.prototype.toJadenCase("Hi there how are you"));

It's not a good practice to add methods on Prototype you can simply write a function and use it

const str = "Hi there how are you?";

const changeFirstChar = (str) => str[0].toUpperCase() + str.substr(1)

const toJadenCase = function(st) {
  let arr = st.split(" ");
  return arr.map(e => changeFirstChar(e))
};

console.log(toJadenCase("Hi there how are you"));

//if you need output as string
console.log(toJadenCase("Hi there how are you").join(' '));
Code Maniac
  • 37,143
  • 5
  • 39
  • 60