Skip to content
Advertisement

Array manipulation error with regex – Kata 6 Codewar

In theory it should transform a given array to camel case. I don’t understand what is wrong

function toCamelCase(str){
 if(str.length === 0) return ""
 let array = str.split(/([_-])/);
 array.forEach(word =>{
   word == "-" ? word.replace("") : word.charAt(0).toUpperCase()
 })
  
 return array
}

Advertisement

Answer

The .replace() method doesn’t modify the word variable, it instead returns a new modified string. So your code is producing new values within the loop but doesn’t do anything with those values. Moreover, word here is a value and not a reference to your array values, so you can’t modify them directly from within your forEach() loop and expect it to modify the string values from your array. You instead need to create a new array, with each element transformed, which can be done by using .map() and returning the new value:

function toCamelCase(str) {
  const array = str.split(/[_-]/);
  return array.map((word, i) => {
    return i === 0 ? word : word.charAt(0).toUpperCase() + word.slice(1)
  }).join("");
}

console.log(toCamelCase("this-is-some-text"));

Note that you can remove the capturing group from your .split() to remove the _ and - chars from your array so that you don’t need to remove them when you map.

Note that for something like this, if you’re already using regular expressions in your .split(), you might consider using .replace() with a replacement function, for example, something like:

function toCamelCase(str) {
  return str.replace(/-w/g, ([,m]) => m.toUpperCase());
}

console.log(toCamelCase("this-is-some-text"));
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement