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?

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

or even shorter approach with regex :P
@NickParsons, of course, but i think, op would like to learn without.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.