0

My steps go through and put the string into an array, then I loop to find spaces and uppercase the letter at the following index, then after that if statement is done I want to push all the chars that aren't spaces to a new array and join but my capitalized letters aren't showing in the final array.

var camelCase = function(str) {
  console.log(str)
  let upCased;
  let finalStr = [];
  let camelCase = str.toLowerCase().split("");

  for (let i = 0; i < camelCase.length; i++) {
    if (camelCase[i] == ' ') {
      letter = camelCase[i + 1]
      upCased = letter.toUpperCase();
      console.log(upCased)
    }

    if (camelCase[i] !== ' ') {
      finalStr.push(camelCase[i])
    }
  }
  console.log(finalStr.join(""))
};

camelCase("now is the time to come to the aid")
mplungjan
  • 169,008
  • 28
  • 173
  • 236
mcilhaggis
  • 55
  • 1
  • 10
  • [Does this answer your question?](https://stackoverflow.com/questions/41048336/auto-capitalize-only-the-first-letter-of-each-word-in-an-input-field/41048432#41048432) – Scott Marcus Jan 05 '21 at 21:16
  • 1
    You dont do anything with upCased after you assign to it – Achtung Jan 05 '21 at 21:16
  • Strings are copied by value, thus your touppercase has no effect on the camelCase array. `camelCase[I+1] = upCase` will give you the correct behavior – Ted Brownlow Jan 05 '21 at 21:18
  • As well as the `upCased` issue already mentioned, you will process the `b` in `foo bar` twice: Once when you hit the space at index 3 and again when you hit the `b` at 4, yielding `fooBbar`, presumably not what you wanted. – Scott Sauyet Jan 05 '21 at 21:20
  • 1
    As the comments and answers show you how to fix your code, note also the simple one-liner, `const camelCase = (s) => s .replace (/\s+(\S)/g, (a, s) => s .toUpperCase ())`. – Scott Sauyet Jan 05 '21 at 21:27
  • @ScottMarcus: I think that answer, while fine on it's own, has too many other concerns beyond the string manipulation needed here. – Scott Sauyet Jan 05 '21 at 21:30
  • @ScottSauyet Yup, that's why I didn't close this as a dupe. – Scott Marcus Jan 05 '21 at 21:32

4 Answers4

3

As the others pointed out in the comments, you aren't doing anything with upCased. Secondly, you should increase i by one when encountering space - right now even if you saved capital letter, small one would appear next to it. And you don't need this last if (else is enough). In the end it should be:

var camelCase = function(str) {
    console.log(str)
    let upCased;
    let finalStr = [];
    let camelCase = str.toLowerCase().split("");
    let letter = "";

    for(let i = 0; i < camelCase.length; i++){
        if (camelCase[i] == ' '){
            letter = camelCase[i + 1]
            upCased = letter.toUpperCase();
            console.log(upCased);
            finalStr.push(upCased); // Added this
            i++;                    // and that
        }
        
        else {                      // and changed that line
            finalStr.push(camelCase[i])
        }
    }
    console.log(finalStr.join(""))
};
Voodu
  • 770
  • 7
  • 18
2

To provide a different type of solution that's a bit less complicated, you could split the string at spaces, use map to iterate through them:

  • On the first index, return the lowercase word
  • On all other indices, return the first letter uppercased, and concatenate it to a substring of the rest of the word.

Something like the following:

var camelCase = function(str){
    return str.split(' ').map((v,i) => {
        return (i > 0) ? v[0].toUpperCase() + v.substring(1,v.length).toLowerCase() : v.toLowerCase();
    }).join('');
};
  
console.log( camelCase("ThIs is a tesTinG stRING") ); // thisIsATestingString
Xhynk
  • 13,513
  • 8
  • 32
  • 69
  • Thank you for your reply! I was trying to use basic Javascript with no fancy functions but this is a great answer if I were. – mcilhaggis Jan 05 '21 at 21:35
  • 1
    `.map` isn't too fancy! At it's core, it's just another iterative controller. I +1'd the other accepted answer, because like you mentioned it fixed your existing code and illustrated the necessary changes with comments. Just wanted to show another method entirely (rarely is there ever just one way to do things in any language!). I was halfway through an answer like that one but they beat me to it, so didn't want to leave it hanging, so came up with a different solution. Cheers! – Xhynk Jan 05 '21 at 21:39
2

Here's an alternative form, with ES6 by using arrow functions and chaining method calls. Start by splitting the string into words, capitalize each one then join back again into a string:

capitalize = x => x.charAt(0).toUpperCase() + x.slice(1)

toCamelCase = w => w.toLowerCase()
                    .split(' ')
                    .map((x, i) => i == 0 ? x : capitalize(x))
                    .join('')

console.log(toCamelCase('this is nice'))
Ivan
  • 34,531
  • 8
  • 55
  • 100
0

Here is a reduce version

var camelCase = str => str
  .toLowerCase()
  .split(/\s+/).reduce(
    (acc, word, i) => {
      acc.push(i === 0 ? word : word.slice(0, 1).toUpperCase() + word.slice(1));
      return acc;
    }, []).join("")

console.log(
  camelCase("now is the time to come to the aid")
)
mplungjan
  • 169,008
  • 28
  • 173
  • 236