Complete the function/method so that it takes CamelCase string and returns the string in snake_case notation. Lowercase characters can be numbers. If method gets number, it should return string.
Examples:
console.log(toUnderscore('TestController'));// test_controller
console.log(toUnderscore('MoviesAndBooks'));// movies_and_books
console.log(toUnderscore('App7Test'));//app7_test
console.log(toUnderscore(1));// 1
my answer
function toUnderscore(str) {
if (/([a-zd])([A-Z])/g.test(str) == false){
return str;
}
var strnew = str.replace(/([a-zd])([A-Z])/g,'$1_$2')
return strnew.toLowerCase();
}
best answer:
function toUnderscore(string) {
return (''+string).replace(/(.)([A-Z])/g, '$1_$2').toLowerCase();
}