生成随机字符串
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;
};
字符串首字母大写
export const fistLetterUpper = (str) => {
return str.charAt(0).toUpperCase() + str.slice(1);
};
手机号中间四位变成*
export const telFormat = (tel) => {
tel = String(tel);
return tel.substr(0,3) + "****" + tel.substr(7);
};
驼峰命名转换成短横线命名
export const getKebabCase = (str) => {
return str.replace(/[A-Z]/g, (item) => '-' + item.toLowerCase())
}
短横线命名转换成驼峰命名
export const getCamelCase = (str) => {
return str.replace( /-([a-z])/g, (i, item) => item.toUpperCase())
}
全角转换为半角
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;
}
半角转换为全角
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;
}
以上是编程学习网小编为您介绍的“JavaScript开发小技巧之字符串”的全面内容,想了解更多关于 vuejs 内容,请继续关注编程基础学习网。
沃梦达教程
本文标题为:JavaScript开发小技巧之字符串
猜你喜欢
- JavaScript webpack模块打包器如何优化前端性能 2022-10-21
- SpringBoot+Vue3前后端分离,实战wiki知识库系统 2023-10-08
- ZeroClipboard插件实现多浏览器复制功能(支持firefox、chrome、ie6) 2024-02-21
- javascript 特性检测并非浏览器检测 2024-01-16
- AJax与Jsonp跨域访问问题小结 2022-10-18
- 详解JS中continue关键字和break关键字的区别 2022-08-31
- 浅析JSONP技术原理及实现 2024-01-15
- vue总结 2023-10-08
- 在数组中通过find遍历需要的对象 2024-12-07
- linux – HTML到PDF(使用谷歌chrome API)? 2023-10-25