1. 前言
- 各種空格 前后中間的去除也是開發(fā)常見的需求
- 英文字母大小寫轉(zhuǎn)換
2. 去除空格 代碼
/**
* @description 去除空格
* @param String str 需要去除空格的字符串
* @param String pos both(左右)|left|right|all 默認(rèn)both
*/
const trimStr=(str, pos = "both")=> {
str = String(str);
if (pos == "both") {
return str.replace(/^\s+|\s+$/g, "");
}
if (pos == "left") {
return str.replace(/^\s*/, "");
}
if (pos == "right") {
return str.replace(/(\s*$)/g, "");
}
if (pos == "all") {
return str.replace(/\s+/g, "");
}
return str;
},
3. 英文字母大小寫轉(zhuǎn)換代碼
/**
* @desc 英文字母大小寫轉(zhuǎn)換:
* @param {str} 需要處理的英文字符串
* @param {type} 1:首字母大寫 2:首字母小寫 3:大小寫轉(zhuǎn)換 4:全部大寫 5:全部小寫
**/
const changeCase = (str, type) => {
type = type || 1;
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;
}
},
參考資料
初心
我所有的文章都只是基于入門甫窟,初步的了解枣购;是自己的知識(shí)體系梳理,如有錯(cuò)誤,道友們一起溝通交流;
如果能幫助到有緣人,非常的榮幸,一切為了部落
的崛起;
共勉