306 字
2 分钟
实现驼峰和下划线命名转换
① 驼峰 => 下划线
/**
* @desc 驼峰 => 下划线
* @param {String} HumpStr
* @returns 下划线命名
*/
const HumpToline = (HumpStr) => {
// (?<=.) 兼容大驼峰的情况
return HumpStr.replace(/(?<=.)([A-Z])/g, "_$1").toLowerCase();
};
②下划线 => 驼峰
/**
* @desc 下划线 => 驼峰
* @param {String} LineStr
* @returns 驼峰命名
*/
const LineToHump = (LineStr) => {
return LineStr.replace(/\_(\w)/g, (all, letter) => letter.toUpperCase());
};
③数据对象key的 驼峰 <=> 下划线 相互转换
/**
* 数据对象key 驼峰下划线互相转化
* @param {Object} data 需要转换的对象
* @param {String} type hump-转驼峰 toLine-转下划线
*/
const HumpLineTransfer = (data, type = 'hump') => {
let hump = '';
// 处理对象中的每个key
const TransferKey = (data) => {
if (data instanceof Array) {
data.forEach(item => TransferKey(item));
} else if (data instanceof Object) {
for (const key in data) {
hump = type === 'hump' ? LineToHump(key) : HumpToLine(key);
data[hump] = data[key];
if (key !== hump) {
delete data[key];
}
if (data[hump] instanceof Object) {
HumpLineTransfer(data[hump]);
}
}
} else if (typeof data === 'string') {
data = type === 'hump' ? LineToHump(data) : HumpToLine(data);
}
};
TransferKey(data);
return data;
};
④css属性名 <=> 驼峰
/**
* css属性名 转 驼峰
* @param {string} propertyName
*/
const toHump = (propertyName) => {
if (propertyName[0] === '-') {
// 忽略开头的'-'
propertyName = propertyName.substring(1, propertyName.length);
}
return propertyName.replace(/-(\w)/g, (all, letter) => letter.toUpperCase());
};
console.log(toHump('-webkit-line-clamp')); // webkitLineClamp
console.log(toHump('font-size')); // fontSize
/**
* 驼峰 转 Css属性名
* @param {string} sName
*/
const toPropertyName = (sName) => {
return sName.replace(/([A-Z])/g, "-$1").toLowerCase();
};
console.log(toHump('webkitLineClamp')); // -webkit-line-clamp
console.log(toHump('fontSize')); // font-size