字符串操作
howcode 2022-12-30 0 javascript
# 生成随机字符串
export const randomString = (len) => {
let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789';
let strLen = chars.length;
let randomStr = '';
for (let i = 0; i < len; i++) {
randomStr += chars.charAt(Math.floor(Math.random() * strLen));
}
return randomStr;
};
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 生成随机颜色
export const randomColor= () =>{
let str = "#";
let random = 0;
let aryNum = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
for(let i = 0; i < 6; i++) {
random = parseInt(Math.random() * 16);
str += aryNum[random];
}
return str;
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 字符串首字母大写
export const fistLetterUpper = (str) => {
return str.charAt(0).toUpperCase() + str.slice(1);
};
1
2
3
2
3
# 手机号中间四位变成*
export const telFormat = (tel) => {
tel = String(tel);
return tel.substr(0,3) + "****" + tel.substr(7);
};
1
2
3
4
2
3
4
# 驼峰命名转换成短横线命名
export const getKebabCase = (str) => {
return str.replace(/[A-Z]/g, (item) => '-' + item.toLowerCase())
}
1
2
3
2
3
# 短横线命名转换成驼峰命名
export const getCamelCase = (str) => {
return str.replace( /-([a-z])/g, (i, item) => item.toUpperCase())
}
1
2
3
2
3
# 全角转换为半角
export const toCDB = (str) => {
let result = "";
for (let i = 0; i < str.length; i++) {
code = str.charCodeAt(i);
if (code >= 65281 && code <= 65374) {
result += String.fromCharCode(str.charCodeAt(i) - 65248);
} else if (code == 12288) {
result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
} else {
result += str.charAt(i);
}
}
return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 半角转换为全角
export const toDBC = (str) => {
let result = "";
for (let i = 0; i < str.length; i++) {
code = str.charCodeAt(i);
if (code >= 33 && code <= 126) {
result += String.fromCharCode(str.charCodeAt(i) + 65248);
} else if (code == 32) {
result += String.fromCharCode(str.charCodeAt(i) + 12288 - 32);
} else {
result += str.charAt(i);
}
}
return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 判断字符串是否为空
export const isEmptyString = (string) =>{
if (string == undefined ||
typeof string == "undefined" ||
!string ||
string == null ||
string == '' ||
/^\s+$/gi.test(string)) {
return true;
} else {
return false;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
评论
- 表情
——暂无评论——