正则表达式的奇淫技巧
驼峰名转下划线:
'componentMapModelRegistry'.match(/^[a-z][a-z0-9]+|[A-Z][a-z0-9]*/g).join('_').toLowerCase(); // component_map_model_registry
获取URL参数
function wordCount(data) { var pattern = /[a-zA-Z0-9_\u0392-\u03c9]+|[\u4E00-\u9FFF\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\uac00-\ud7af]+/g; var m = data.match(pattern); var count = 0; if( m === null ) return count; for (var i = 0; i < m.length; i++) { if (m[i].charCodeAt(0) >= 0x4E00) { count += m[i].length; } else { count += 1; } } return count; } var text = '贷款买房,也意味着你能给自己的资产加杠杆,能够撬动更多的钱,来孳生更多的财务性收入。'; wordCount(text); // 38
特殊字符转义
function htmlspecialchars (str) { var str = str.toString().replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"'); return str; } htmlspecialchars('&jfkds<>'); // "&jfkds<>"
格式化数量
// 方法一 function formatNum (num, n) { if (typeof num == "number") { num = String(num.toFixed(n || 0)); var re = /(-?\d+)(\d{3})/; while (re.test(num)) num = num.replace(re, "$1,$2"); return num; } return num; } formatNum(2313123, 3); // "2,313,123.000" // 方法二 '2313123'.replace(/\B(?=(\d{3})+(?!\d))/g, ','); // "2,313,123" // 方法三 function formatNum(str) { return str.split('').reverse().reduce((prev, next, index) => { return ((index % 3) ? next : (next + ',')) + prev }); }
测试质数
var arr = 'abcdaabc'; var info = arr .split('') .reduce((p, k) => (p[k]++ || (p[k] = 1), p), {}); console.log(info); //{ a: 3, b: 2, c: 2, d: 1 }
如何优雅的实现金钱格式化:1234567890 --> 1,234,567,890
var test1 = '1234567890' var format = test1.replace(/\B(?=(\d{3})+(?!\d))/g, ',') console.log(format) // 1,234,567,890
代码来自于收集,方便学习
相关推荐
wangzhaotongalex 2020-10-20
wyq 2020-11-11
TLROJE 2020-10-26
风雨断肠人 2020-10-13
duanqingfeng 2020-09-29
rechanel 2020-11-16
cshanzhizi 2020-10-16
luofuIT成长记录 2020-09-22
phphub 2020-09-10
taomengxing 2020-09-07
MaggieRose 2020-08-19
flyingssky 2020-08-18
山水沐光 2020-08-18
jyj00 2020-08-15
AHuqihua 2020-08-09
山水沐光 2020-08-03