Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Break Camel Case function in JavaScript

I have been attempting to solve this codewars problem for a while in JavaScript:

"Complete the solution so that the function will break up camel casing, using a space between words. Example:"

"camelCasing"  =>  "camel Casing"

"identifier"   =>  "identifier"

""             =>  ""

I have it almost all the way, but for some reason my code is selecting the wrong space to add a blank space.
I’m hoping someone can tell me what I am doing wrong.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function solution(string) {
  let splitStr = string.split("");
  let newStr = string.split("");
  let capStr = string.toUpperCase().split("");
  for (i = 0; i < splitStr.length; i++) {
    if (splitStr[i] === capStr[i]) {
      newStr.splice(i, 0, ' ');
    }
  }
  return newStr.join("");
}

console.log('camelCasing: ', solution('camelCasing'));
console.log('camelCasingTest: ', solution('camelCasingTest'));

>Solution :

The first insertion into newStr will be at the correct spot, but after that insertion of the space, the letters that follow it in newStr will be at an increased index. This means that when the next capital is found at i in splitStr (which did not change), the insertion into newStr (which did change) should really be at i+1.

A solution is to make your loop iterate from end to start:

function solution(string) {
  let splitStr = string.split("");
  let newStr = string.split("");
  let capStr = string.toUpperCase().split("");
  for (i = splitStr.length - 1; i >= 0; i--) {
    if (splitStr[i] === capStr[i]) {
      newStr.splice(i, 0, ' ');
    }
  }
  return newStr.join("");
}

console.log('camelCasing: ', solution('camelCasing'));
console.log('camelCasingTest: ', solution('camelCasingTest'));

This kind of problem is however much easier solved with a regular expression:

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

console.log('camelCasing: ', solution('camelCasing'));
console.log('camelCasingTest: ', solution('camelCasingTest'));

Explanation of the regular expression:

  • [A-Z] a capital letter from the Latin alphabet.
  • $& backreference to the matched letter, used in the replacement.
  • g global flag so all matches are replaced.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading