web-utils-super
Version:
前端函数库
43 lines (41 loc) • 1.13 kB
JavaScript
/**
* @desc: 字符转换,type: 1:首字母大写 2:首字母小写 3:大小写转换 4:全部大写 5:全部小写 默认为1
* @param {String} str 字符串
* @param {Number} type 转换方式
* @return {String}
*/
function changeCase(str, type = 1) {
type = type || 4;
switch (type) {
case 1:
return str.replace(/\b\w+\b/g, function (word) {
return (
word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()
);
});
case 2:
return str.replace(/\b\w+\b/g, function (word) {
return (
word.substring(0, 1).toLowerCase() + word.substring(1).toUpperCase()
);
});
case 3:
return str
.split("")
.map(function (word) {
if (/[a-z]/.test(word)) {
return word.toUpperCase();
} else {
return word.toLowerCase();
}
})
.join("");
case 4:
return str.toUpperCase();
case 5:
return str.toLowerCase();
default:
return str;
}
}
module.exports = changeCase