防止转义符转义

  1. const path = `C:\web\index.html`; // 'C:web.html'
  2. const unescapedPath = String.raw`C:\web\index.html`; // 'C:\web\index.html'

获取字符数

String

存在 Unicode 码点大于0xFFFF的字符时, 使用 for of 获取字符数

  1. String.prototype.charLength = function () {
  2. let length = 0;
  3. for (let chat of this) {
  4. length += 1;
  5. }
  6. return length;
  7. };
  8. let s = "𠮷🎈";
  9. function charLength(str) {
  10. let length = 0;
  11. for (let char of str) {
  12. length += 1;
  13. }
  14. return length;
  15. }
  16. console.log(
  17. "🚀 ~ file: byteLength.js:15 ~ charLength ~ charLength:",
  18. charLength(s),
  19. s.charLength()
  20. );

image.png

去除首尾空格 - trim()

  1. function myTrim(str) {
  2. return str.replace(/(^\s+)|(\s+$)/g,'')//将前空格和后空格替换为空
  3. }

获取字符串字节大小

  1. const byteSize = str => new Blob([str]).size;
  2. byteSize('😀'); // 4
  3. byteSize('Hello World'); // 11

字符串格式化、美化

超出数量显示…

  1. // 简单按字符长度截取
  2. if (row.length > 28) {
  3. row = row.slice(0, 13) + '...'
  4. }
  1. // 按byte长度截取
  2. function cutStringByByte(str: string, len: number): string {
  3. if (!str && typeof str != 'undefined') {
  4. return ''
  5. }
  6. let num = 0
  7. let subStr = ''
  8. for (const i of str) {
  9. num += i.charCodeAt(0) > 255 ? 2 : 1
  10. if (num > len) {
  11. subStr += '...'
  12. break
  13. } else {
  14. subStr += i
  15. }
  16. }
  17. return subStr
  18. }

连字符与驼峰互转 camelize & hyphenate

  1. // 将函数变为可缓存结果的函数
  2. const cacheStringFunction = (fn) => {
  3. const cache = Object.create(null);
  4. return (str) => {
  5. const hit = cache[str];
  6. return hit || (cache[str] = fn(str));
  7. };
  8. };
  9. // 连字符转驼峰
  10. const camelizeRE = /-(\w)/g;
  11. const camelize = cacheStringFunction((str) => {
  12. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ""));
  13. });
  14. // 清爽版
  15. // const camelize = str => str.replace(camelizeRE, (_, c) => { return c ? c.toUpperCase() : '';
  16. // });
  17. // 举例:
  18. console.log("🚀 ~ file: test.js ~ line 10 ~ camelize", camelize("on-click-a"));
  19. // 驼峰转连字符
  20. const hyphenateRE = /\B([A-Z])/g;
  21. const hyphenate = cacheStringFunction((str) =>
  22. str.replace(hyphenateRE, "-$1").toLowerCase()
  23. );
  24. // 清爽版const
  25. // hyphenate = str => str.replace(hyphenateRE, '-$1').toLowerCase();
  26. // 仿照 camelize 写法
  27. // const hyphenate = (str) =>
  28. // str.replace(hyphenateRE, (_, c) => {
  29. // return c ? `-${c.toLowerCase()}` : "";
  30. // });
  31. // 举例:onClickA => on-click-ahyphenate('onClickA');
  32. console.log("🚀 ~ file: test.js ~ line 10 ~ camelize", hyphenate("onClickA"));

base64 编解码

基于atob和btoa的base64编码和解码

  1. function utf8_to_b64( str ) {
  2. return window.btoa(unescape(encodeURIComponent( str )));
  3. }
  4. function b64_to_utf8( str ) {
  5. return decodeURIComponent(escape(window.atob( str )));
  6. }
  7. utf8_to_b64('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
  8. b64_to_utf8('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"

不依赖浏览器环境

  1. /**
  2. * base64编码和解码
  3. * @param str
  4. * @returns
  5. */
  6. const base64 = {
  7. _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
  8. encode: function (e: string) {
  9. let t = "";
  10. let n: number,
  11. r: number,
  12. i: number,
  13. s: number,
  14. o: number,
  15. u: number,
  16. a: number;
  17. let f = 0;
  18. e = base64._utf8_encode(e);
  19. while (f < e.length) {
  20. n = e.charCodeAt(f++);
  21. r = e.charCodeAt(f++);
  22. i = e.charCodeAt(f++);
  23. s = n >> 2;
  24. o = ((n & 3) << 4) | (r >> 4);
  25. u = ((r & 15) << 2) | (i >> 6);
  26. a = i & 63;
  27. if (isNaN(r)) {
  28. u = a = 64;
  29. } else if (isNaN(i)) {
  30. a = 64;
  31. }
  32. t =
  33. t +
  34. this._keyStr.charAt(s) +
  35. this._keyStr.charAt(o) +
  36. this._keyStr.charAt(u) +
  37. this._keyStr.charAt(a);
  38. }
  39. return t;
  40. },
  41. decode: function (e: string) {
  42. let t = "";
  43. let n: number, r: number, i: number;
  44. let s: number, o: number, u: number, a: number;
  45. let f = 0;
  46. e = e.replace(/[^A-Za-z0-9+/=]/g, "");
  47. while (f < e.length) {
  48. s = this._keyStr.indexOf(e.charAt(f++));
  49. o = this._keyStr.indexOf(e.charAt(f++));
  50. u = this._keyStr.indexOf(e.charAt(f++));
  51. a = this._keyStr.indexOf(e.charAt(f++));
  52. n = (s << 2) | (o >> 4);
  53. r = ((o & 15) << 4) | (u >> 2);
  54. i = ((u & 3) << 6) | a;
  55. t = t + String.fromCharCode(n);
  56. if (u != 64) {
  57. t = t + String.fromCharCode(r);
  58. }
  59. if (a != 64) {
  60. t = t + String.fromCharCode(i);
  61. }
  62. }
  63. t = base64._utf8_decode(t);
  64. return t;
  65. },
  66. _utf8_encode: function (e: string) {
  67. e = e.replace(/rn/g, "n");
  68. let t = "";
  69. for (let n = 0; n < e.length; n++) {
  70. let r = e.charCodeAt(n);
  71. if (r < 128) {
  72. t += String.fromCharCode(r);
  73. } else if (r > 127 && r < 2048) {
  74. t += String.fromCharCode((r >> 6) | 192);
  75. t += String.fromCharCode((r & 63) | 128);
  76. } else {
  77. t += String.fromCharCode((r >> 12) | 224);
  78. t += String.fromCharCode(((r >> 6) & 63) | 128);
  79. t += String.fromCharCode((r & 63) | 128);
  80. }
  81. }
  82. return t;
  83. },
  84. _utf8_decode: function (e: string) {
  85. let t = "",
  86. n = 0,
  87. r = 0,
  88. c2 = 0,
  89. c3 = 0;
  90. while (n < e.length) {
  91. r = e.charCodeAt(n);
  92. if (r < 128) {
  93. t += String.fromCharCode(r);
  94. n++;
  95. } else if (r > 191 && r < 224) {
  96. c2 = e.charCodeAt(n + 1);
  97. t += String.fromCharCode(((r & 31) << 6) | (c2 & 63));
  98. n += 2;
  99. } else {
  100. c2 = e.charCodeAt(n + 1);
  101. c3 = e.charCodeAt(n + 2);
  102. t += String.fromCharCode(
  103. ((r & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)
  104. );
  105. n += 3;
  106. }
  107. }
  108. return t;
  109. },
  110. };
  111. export default base64;

颜色转换

JavaScript颜色转换的核心就是进制间的转换。RGB格式其实就是十进制表示法,所以,十六进制颜色与RGB颜色的转换就是十六进制与十进制之间的转换。

十六进制转换为十进制相对容易些,核心代码如下示例:parseInt("0xFF"),其结果就是255,”0x”就表明当前是16进制,由于parseInt后面无参数,默认就是转换为10进制了。

十进制转换为16进制,核心代码如下:var r=255; r.toString(16);,其结果是FF。”16″表示数值转换为16进制字符串。

  1. const hexToRGB = hex => {
  2. let alpha = false,
  3. h = hex.slice(hex.startsWith('#') ? 1 : 0);
  4. if (h.length === 3) h = [...h].map(x => x + x).join('');
  5. else if (h.length === 8) alpha = true;
  6. h = parseInt(h, 16);
  7. return (
  8. 'rgb' +
  9. (alpha ? 'a' : '') +
  10. '(' +
  11. (h >>> (alpha ? 24 : 16)) +
  12. ', ' +
  13. ((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) +
  14. ', ' +
  15. ((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) +
  16. (alpha ? `, ${h & 0x000000ff}` : '') +
  17. ')'
  18. );
  19. };
  20. hexToRGB('#27ae60ff'); // 'rgba(39, 174, 96, 255)'
  21. hexToRGB('27ae60'); // 'rgb(39, 174, 96)'
  22. hexToRGB('#fff'); // 'rgb(255, 255, 255)'
  1. const RGBToHex = (r, g, b) =>
  2. ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
  3. RGBToHex(255, 165, 1); // 'ffa501'
  1. const RGBToHSB = (r, g, b) => {
  2. r /= 255;
  3. g /= 255;
  4. b /= 255;
  5. const v = Math.max(r, g, b),
  6. n = v - Math.min(r, g, b);
  7. const h =
  8. n === 0 ? 0 : n && v === r ? (g - b) / n : v === g ? 2 + (b - r) / n : 4 + (r - g) / n;
  9. return [60 * (h < 0 ? h + 6 : h), v && (n / v) * 100, v * 100];
  10. };
  11. RGBToHSB(252, 111, 48);
  12. // [18.529411764705856, 80.95238095238095, 98.82352941176471]
  1. const RGBToHSL = (r, g, b) => {
  2. r /= 255;
  3. g /= 255;
  4. b /= 255;
  5. const l = Math.max(r, g, b);
  6. const s = l - Math.min(r, g, b);
  7. const h = s
  8. ? l === r
  9. ? (g - b) / s
  10. : l === g
  11. ? 2 + (b - r) / s
  12. : 4 + (r - g) / s
  13. : 0;
  14. return [
  15. 60 * h < 0 ? 60 * h + 360 : 60 * h,
  16. 100 * (s ? (l <= 0.5 ? s / (2 * l - s) : s / (2 - (2 * l - s))) : 0),
  17. (100 * (2 * l - s)) / 2,
  18. ];
  19. };
  20. RGBToHSL(45, 23, 11); // [21.17647, 60.71428, 10.98039]
  1. const HSBToRGB = (h, s, b) => {
  2. s /= 100;
  3. b /= 100;
  4. const k = (n) => (n + h / 60) % 6;
  5. const f = (n) => b * (1 - s * Math.max(0, Math.min(k(n), 4 - k(n), 1)));
  6. return [255 * f(5), 255 * f(3), 255 * f(1)];
  7. };
  8. HSBToRGB(18, 81, 99); // [252.45, 109.31084999999996, 47.965499999999984]
  1. const HSLToRGB = (h, s, l) => {
  2. s /= 100;
  3. l /= 100;
  4. const k = n => (n + h / 30) % 12;
  5. const a = s * Math.min(l, 1 - l);
  6. const f = n =>
  7. l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));
  8. return [255 * f(0), 255 * f(8), 255 * f(4)];
  9. };
  10. HSLToRGB(13, 100, 11); // [56.1, 12.155, 0]

color 配色

uuid生成随机 字符串

  1. /**
  2. * 生成随机id
  3. * @param {*} length
  4. * @param {*} chars
  5. */
  6. export function uuid(length, chars) {
  7. chars =
  8. chars ||
  9. '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  10. length = length || 8
  11. var result = ''
  12. for (var i = length; i > 0; --i)
  13. result += chars[Math.floor(Math.random() * chars.length)]
  14. return result
  15. }

基于URL或者Crypto.getRandomValues生成UUID

  1. function genUUID() {
  2. const url = URL.createObjectURL(new Blob([]));
  3. // const uuid = url.split("/").pop();
  4. const uuid = url.substring(url.lastIndexOf('/')+ 1);
  5. URL.revokeObjectURL(url);
  6. return uuid;
  7. }
  8. genUUID() // cd205467-0120-47b0-9444-894736d873c7
  9. function uuidv4() {
  10. return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
  11. (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  12. }
  13. uuidv4() // 38aa1602-ba78-4368-9235-d8703cdb6037
  14. //chrome 92支持
  15. crypto.randomUUID()

基于toLocaleString千分位

  1. function formatMoney(num){
  2. return (+num).toLocaleString("en-US");
  3. }
  4. console.log(formatMoney(123456789)); // 123,456,789
  5. console.log(formatMoney(6781)) // 6,781
  6. console.log(formatMoney(5)) // 5
  7. //超大的数
  8. formatMoney(19999999933333333333333) // 19,999,999,933,333,333,000,000

内容脱敏

在一些涉及到用户隐私情况下,可能会遇到对用户的手机号身份证号之类的信息脱敏,但是这个脱敏数据的规则是根据用户信息要脱敏字段动态的生成的,此时我们动态拼接正则来实现一个动态脱敏规则

  1. const encryptReg = (before = 3, after = 4) => {
  2. return new RegExp('(\\d{' + before + '})\\d*(\\d{' + after + '})');
  3. };
  4. // 使用:'13456789876'.replace(encryptReg(), '$1****$2') -> "134****9876"
  1. // 手机号中间四位变成*
  2. export const telFormat = (tel) => {
  3. tel = String(tel);
  4. return tel.substr(0,3) + "****" + tel.substr(7);
  5. };

搜索

  1. // select下拉组件的搜索
  2. function filterTableOption(input: string, option: any) {
  3. return (
  4. JSON.parse(option.value)
  5. .table_name.toLowerCase()
  6. .indexOf(input.toLowerCase()) >= 0 ||
  7. JSON.parse(option.value)
  8. .schema_name.toLowerCase()
  9. .indexOf(input.toLowerCase()) >= 0
  10. )
  11. }
  12. // sourceString.toLowerCase().indexOf(targetString.toLowerCase()) >= 0