Rory Dowse

Software Engineer

Coding Challenge: Break camelCase and Immutable Strings

In the Break camelCase challenge, the developer is tasked to “Complete the solution so that the function will break up camel casing, using a space between words.”

At first glance, the following pseudocode may seem sufficient:

// parse through the string
// check if the index is equal to toUpperCase
// if true, insert a space
// return the string

However, this approach will not work as intended because strings in JavaScript are immutable. This means they cannot be modified in place, and a new string must be created instead.

To solve this challenge, the following steps should be followed:

  1. Initialize a new empty string
  2. Perform work on the original string
  3. Append characters to the new string
  4. Return the new string

Since the original string cannot be directly modified, appending changes to a new string ensures the desired result:

function solution(string) {
  // Step 1: Initialize a new empty string
  let result = "";

  // Step 2: Perform work on the original string
  for (let i = 0; i < string.length; i++) {
    // Check if the character is uppercase
    if (string[i] === string[i].toUpperCase() && string[i] !== string[i].toLowerCase()) {
      // Step 3: Append a space before the uppercase letter
      result += " ";
    }
    // Append the current character to the result
    result += string[i];
  }

  // Step 4: Return the new string
  return result;
}

While this solution works well, a simpler and more concise approach using regex can also solve the problem effectively:

function solution(string) {
  return string.replace(/([A-Z])/g, ' $1');
}

Here's how the regex solution works:

Both methods demonstrate the importance of understanding how strings behave in JavaScript.

The key takeaways from this challenge are: