Search code examples
javascriptarraysalgorithmuppercasecamelcasing

Finding uppercase letters


I am trying to find the uppercase letters and put a space before them to cut the string into words , but instead getting all the uppercase letter and inserting the space it inserts the space every after the same amount of letters after the first one was found. Like if it is "camelCasingTest" the result will be "camel Casin gTest"

function camelCase(string) {
    let splittedString = string.split('')

    for(let i = 0; i < splittedString.length; i++){
       if(string.charAt(i) === str.charAt(i).toUpperCase()){
        splittedString.splice(i, 0, ' ')
        // i - where the change should be
        // 0 - how many elements should be removed
        // " " - what element should be inserted
        i++
        // The i++ statement ensures that the loop skips the inserted space and continues to the next character.
       }
    }
    return splittedString.join('')
}

I tried using regex and it worked, but this problem is bothering me, any suggestions?


Solution

  • Your comparison should be using the new array rather than the source string. Otherwise, you get index drift as you inject items into the array.

    function camelCase(str) {
      const chars = str.split('');
      for (let i = 0; i < chars.length; i++) {
        // check the array rather than the original string
        if (chars[i] === chars[i].toUpperCase()) {
          chars.splice(i, 0, ' ');
          i++;
        }
      }
      return chars.join('');
    }
    console.log(camelCase('camelCasingTest'));