0

I have a function that should capitalize every first letter in each word in a string, but somehow it delivers incorrect result, any idea why? I need to fix it a bit.

So the input: hello dolly output: Hello Dolly.

Spaces are correctly counted but the capitalization is incorrect.

function letterCapitalize(str) {
  str = str.replace(str.charAt(0), str.charAt(0).toUpperCase());
  let spaces = [];
  for (let i = 0; i < str.length; i++) {
    if (str[i] === ' ') spaces.push(i);
  }
  for (let space of spaces) {
    str = str.replace(str.charAt(space + 1), str.charAt(space + 1).toUpperCase());
  }
  return str;
}

console.log(letterCapitalize("hello there, how are you?"));
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Z. Bird
  • 50
  • 11

2 Answers2

1

// Option One

function capitalize1( str ) {
  let result = str[ 0 ].toUpperCase();

  for ( let i = 1; i < str.length; i++ ) {
    if ( str[ i - 1 ] === ' ' ) {
      result += str[ i ].toUpperCase();
    } else {
      result += str[ i ];
    }
  }

  return result;
}

// Option Two

function capitalize2(str) {
  const words = [];

  for (let word of str.split(' ')) {
    words.push(word[0].toUpperCase() + word.slice(1));
  }

  return words.join(' ');
}

console.log(capitalize1('hello there, how are you?'))
console.log(capitalize2('hello there, how are you?'))
mplungjan
  • 169,008
  • 28
  • 173
  • 236
SakoBu
  • 3,972
  • 1
  • 16
  • 33
0

You could use string.toUpperCase() or if you require more specific logic you could use string.replace() with some regular expression

const letterCapitalize = x => x.toUpperCase();

const letterCapitalizeWithRegex = x => x.replace(/[a-z]/g, l => l.toUpperCase());

console.log("my string".toUpperCase());

console.log(letterCapitalize("my string"));

console.log(letterCapitalizeWithRegex("my string"));
Tibike
  • 338
  • 2
  • 12