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