-1

Good evening Friends! When I try to run the below mentioned function in chrome console, output comes out but minus sign is unreplaced.

function kebabToSnake(kebab){
  var i=0;
  for(i=0;i<kebab.length;i++){
  if(kebab[i]=='-'){
    kebab[i]='_';
  }
  }
  var newStr=kebab;
  return newStr;
}
console.log(kebabToSnake("a-b-c-d"));

Even if i try to return kebab without creating newStr , still does not work . I already know the replace method in javascript . Just want to know why this method does not work out !

Álvaro González
  • 142,137
  • 41
  • 261
  • 360

1 Answers1

2

You can do kebab.replace(/-/g, '_') but assume that's not an option for you, so you actually want to iterate over the characters and replace them one by one.

Strings in JavaScript are immutable, so kebab[i] = '_' won't work.

You need to split the string in an array of characters using String.prototype.split() and iterate over them while doing the replacements you need, either by replacing the elements (characters) in the array or creating a new one, like in the example below, using Array.prototype.map().

Then, you join the characters again using Array.prototype.join().

function kebabToSnake(str) {
  return str.split('').map((char) => {
    return char === '-' ? '_' : char;
  }).join('');
}

console.log(kebabToSnake('foo-bar-baz'))
Danziger
  • 19,628
  • 4
  • 53
  • 83