Reputation: 19
This should be simple but I am not sure why it isn't working:
function kebabToSnake (str){
var string = "";
var chart = "";
for(i=0; i < str.lenght; i++){
if (str.charAt(i) == "-") {
chart = "_";
string = string + chart;
}
else {
chart = str.charAt(i);
string = string + chart;
}
}
return string
}
I know I could do it with str.replace(/-/g,"_") but I cannot see what's wrong with the above, besides being too long. Any help would be great.
Upvotes: 1
Views: 5438
Reputation: 718
You spelled "length" wrong. ( on line 4 )
It works after the spelling correction.
function kebabToSnake (str){
var string = "";
var chart = "";
for(i=0; i < str.length; i++){ //fixed spelling from 'str.lenght'
if (str.charAt(i) == "-") {
chart = "_";
string = string + chart;
}
else {
chart = str.charAt(i);
string = string + chart;
}
}
return string
}
var body = document.querySelector( 'body' ),
output = kebabToSnake( '-' ); //First test with '-' in conditional statement
body.innerHTML = output; //display to body
output = kebabToSnake( 'Another String' ); //Second test with random text triggering ELSE statement
body.innerHTML += '<br>' + output; //display to body
Upvotes: 3
Reputation: 563
You can achieve this goal by using RegExp more concisely:
function kebabToSnake (str) {
return str.replace(/-/g, '_');
}
Upvotes: -1