javaScript面试题:小骆驼式命名法和下划线法命名法的互相

2019-04-10  本文已影响0人  果然
原创面试题

上周我在一篇介绍正则表达式实例的文章中,写了这么一个面试题:将字符串"the-first-name"变成小驼峰样式。

//面试题: 将字符串"the-first-name"变成小驼峰样式
var reg7 = /-(\w)/g;
var str7 = "the-first-name";
console.log(str7.replace(reg7,function(name, $1){
    return $1.toUpperCase();
}));//theFirstName

如果将上述面试题,反过来问,该怎么回答呢?
反过来问:

面试题:请将小驼峰命名法写的变量和函数的名字theFirstName,转换成下划线命名法的样式"the_first_name".

(注:the-first-name这种命名法不常见,所以改成the_first_name)

var reg7 = /[A-Z]/g;
var str7 = "theFirstName";
console.log(str7.replace(reg7,function($1){
  return '_' + $1.toLowerCase();
}));//the_first_name  

这是直接写的方法,咱们还是把它封装成函数吧:

//封装成函数的写法
 function styleUnderline(name){
    function addUnderline(match){
return '_' + match.toLowerCase();
    }
    return name.replace(/[A-Z]/g, addUnderline);
  }
  console.log(styleUnderline('theFirstName'));//the_first_name

这样,使用时,直接调用函数styleUnderline()即可。

最后,在回顾并修改一下上次写的面试题,

面试题:请将下划线命名法写的变量和函数的名字"the_first_name",转换成小驼峰命名法的样式"theFirstName".

var reg7 = /_(\w)/g;
var str7 = "the_first_name";
console.log(str7.replace(reg7,function(name, $1){
    return $1.toUpperCase();
}));//theFirstName

同样的,我们把它也封装成函数:

function styleCamelCase(name){
    function addCamelCase(match, $1){
return $1.toUpperCase();
    }
    return name.replace(/_(\w)/g, addCamelCase);
  }
  console.log(styleCamelCase('the_first_name'));//theFirstName
上一篇 下一篇

猜你喜欢

热点阅读