1

function kebabToSnake(string){
  var replacedString = string;
  for(i = 0; i < string.length; i++){
    if(string[i] === "-"){
       replacedString[i] = "_";
    }
  }
  return replacedString;
}

I am new in js, can someone explain why this code doesn't work?

Mike Symynyuk
  • 31
  • 1
  • 2

1 Answers1

3

String are immutable, that means, you can not assign a character to a position of the string.

You could use an array instead and relace only the wanted character. Later you need to join the array to a string.

function kebabToSnake(string) {
    var replacedString = Array.from(string);
    for (i = 0; i < string.length; i++){
        if (string[i] === "-"){
            replacedString[i] = "_";
        }
    }
    return replacedString.join('');
}

console.log(kebabToSnake('abc-def-ghi'));

A bit shorter approach by using the mapping parameter of Array.from.

function kebabToSnake(string) {
    return replacedString = Array
        .from(string, c => c === '-' ? '_' : c)
        .join('');
}

console.log(kebabToSnake('abc-def-ghi'));

Finally a regular expression, which looks for a single minus sign /-/ and replaces all (g - for global - flag) with an underscore '_'.

function kebabToSnake(string) {
    return string.replace(/-/g, '_');
}

console.log(kebabToSnake('abc-def-ghi'));
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392