生成随机字符串
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开发小技巧之字符串
基础教程推荐
猜你喜欢
- 基于Vue制作组织架构树组件 2024-04-08
- 浅谈Vue2和Vue3的数据响应 2023-10-08
- this[] 指的是什么内容 讨论 2023-11-30
- 关于文字内容过长,导致文本内容超出html 标签宽度的解决方法之自动换行 2023-10-28
- js禁止页面刷新与后退的方法 2024-01-08
- vue离线环境如何安装脚手架vue-cli 2025-01-19
- 浅析canvas元素的html尺寸和css尺寸对元素视觉的影响 2024-04-26
- CSS3的几个标签速记(推荐) 2024-04-07
- Ajax实现动态加载数据 2023-02-01
- JS前端广告拦截实现原理解析 2024-04-22
