1

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.

3
  • example for input and output? Commented Aug 6, 2017 at 2:38
  • 3
    @basement got the answer. str.length not leght Commented Aug 6, 2017 at 2:43
  • What happens when you debug your code (eg, step through it line-by-line in the debugger)? What do you see? Commented Aug 6, 2017 at 2:48

2 Answers 2

3

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

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

1 Comment

Lol I can't believe I didn't notice, it was driving me crazy. Thank you!!!
-1

You can achieve this goal by using RegExp more concisely:

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

2 Comments

‘coz '-' is a special purpose character in RegExp, so it should be escaped when you use it as a plain character to match.
Yes, maybe you are right. But in practice, I always ask my programmers to escape it 'coz there's no negative effect on correctness.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.