java短横线转驼峰_整理前端面试题(三):驼峰命名法和短横线命名法的转换

近年来由于Vue和Angular等优秀框架的普及, 在框架的使用中常会进行自定义属性名的命名规则的转换.也就是驼峰命名法(camelCase)和短横线命名法(kebab-case)的转换.所以, 在最近的面试题中, 考查两个命名法的转换的面试题时常出现. 下图是Vue.js的官方文档中命名规则的转换的应用场景.

Vue的官方文档

面试题1

将骆驼命名规则的字符串转换成使用短横线命名法的字符串, 并且全小写 .例如: 'getElementById' => 'get-element-by-id'

方法1:采用数组的方法

function getKebabCase ( str ) {

var arr = str.split('');

str = arr.map(function ( item ){

if( item.toUpperCase() === item ){

return '-' + item.toLowerCase();

}else{

return item;

}

}).join( '' );

return str;

}

console.log( getKebabCase( 'getElementById' ) ); //get-element-by-id

方法2:采用正则表达式

function getKebabCase( str ) {

return str.replace( /[A-Z]/g, function( i ) {

return '-' + i.toLowerCase();

})

}

console.log( getKebabCase( 'getElementById' ) ); //get-element-by-id

面试题2

将短横线命名法的字符串转换成使用骆驼命名规则的字符串, 并且全小写 .例如: 'get-element-by-id' => 'getElementById'

方法1:采用数组的方法

function getCamelCase( str ) {

var arr = str.split( '-' );

return arr.map( function( item, index ) {

if( index === 0 ){

return item;

}else{

return item.charAt(0).toUpperCase() + item.slice( 1 );

}

}).join('');

}

console.log( getCamelCase( 'get-element-by-id' ) ); //getElementById

方法2:采用正则表达式

function getCamelCase( str ) {

return str.replace( /-([a-z])/g, function( all, i ){

return i.toUpperCase();

} )

}

console.log( getCamelCase( 'get-element-by-id' ) ); //getElementById

进阶版: 考虑缓存和闭包,依次提高性能和减少污染

进阶版getKebabCase()

var getKebabCase = (function() {

var cache = {};

return function ( str ) {

var ret = cache[ str ];

if( ret ) {

return ret;

}else{

return cache[ str ] = str.replace( /[A-Z]/g, function( i ){

return '-' + i.toLowerCase();

})

}

}

})();

console.log( getKebabCase( 'getElementById' ) );

进阶版getCamelCase()

var getCamelCase = (function() {

var cache = {};

return function ( str ) {

if( cache[ str ] ) {

return cache[ str ];

}else{

return cache[ str ] = str.replace( /-([a-z])/g, function( all, i ) {

return i.toUpperCase();

})

}

}

})()

console.log( getCamelCase( 'get-element-by-id' ) );

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值