JavaScript ----- Convert PascalCase string into snake_case

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-z\d])([A-Z])/g.test(str) == false){
    return str;
  } 
   var strnew = str.replace(/([a-z\d])([A-Z])/g,'$1_$2')
   return strnew.toLowerCase();
}

best answer:

function toUnderscore(string) {
  return (''+string).replace(/(.)([A-Z])/g, '$1_$2').toLowerCase();
}
posted @ 2017-09-10 21:00  芒果夏夏  阅读(205)  评论(0编辑  收藏  举报