Home > Net >  Array manipulation error with regex - Kata 6 Codewar
Array manipulation error with regex - Kata 6 Codewar

Time:08-06

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
}

CodePudding user response:

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"));

CodePudding user response:

word == "-" ? word.replace("") : word.charAt(0).toUpperCase() is just a ternary statement floating in space. This code isn't altering any variables. It's equivalent to:

if(word == "-"){
    word.replace("")
}
else{
    word.charAt(0).toUpperCase()
}

Really, you don't need to mess with arrays if you make use of .replace()'s callback function.

function toCamelCase(str) {
    // Match underscore or dash followed by a letter, case-insensitively
    // Store the letter in a capture group; $1 in this case
    return str.replace( /[_-]([a-z])/gi, function( matches ) {
        // Uppercase the letter
        return matches[ 1 ].toUpperCase()
    } );
}

console.log( toCamelCase( 'to-be_Camel_cased' ) );

  • Related