- 格式化货币(仅转换小数点前的整数局部)
实现成果,遵循的准则: - ==> 123,456,789
123456789.1234 ==> 123,456,789.123
const formatMoney = (money) =>{return money.replace( new RegExp( `(?!^)(?=(\\d{3})+${money.includes('.') ? '\\.' : '$'})`, 'g'), ',' ) )}formatMoney('123456789') // '123,456,789'formatMoney('123456789.123') // '123,456,789.123'formatMoney('123') // '123'formatMoney('123456789.123456')//'123,456,789.123456'
- 实现trim性能的两种形式
去掉字符串首尾的空格
办法1:
const trim1 = (str) => {return str.replace( /^\s*|s*$/g, '' )}const string = ' hello world 'const noSpaceString = 'hello world'const trimString = trim1( string)console.log(string) // hello world console.log(trimString, trimString === noSpaceString)//hello world, trueconsole.log(string) // hello world
办法2:
const trim2 = (str) => { return str.replace(/^\s*(.*?)\s*$/g, '$1') }const string = ' hello medium 'const noSpaceString = 'hello medium'const trimString = trim2(string)console.log(string) // hello medium console.log(trimString, trimString === noSpaceString)//hello medium,trueconsole.log(string)// hello medium
- 解析链接上的搜寻参数
// url https://qianlongo.github.io/vue-demos/dist/index.html?name=fatfish&age=100#/homeconst getQueryByName = (name) => { const queryNameRegex = new RegExp(`[?&]${name}=([^&]*)(&|$)`) const queryNameMatch = window.location.search.match(queryNameRegex) return queryNameMatch ? decodeURIComponent(queryNameMatch[1]) : ''}const name = getQueryByName('name')const age = getQueryByName('age')console.log(name, age) // fatfish, 100
- 驼峰式字符串
示例:
foo Bar => fooBar
foo-bar---- => fooBar
foo_bar__ => fooBar
const camelCase = (string) => { const camelCaseRegex = /[-_\s]+(.)?/g return string.replace(camelCaseRegex, (match, char) => { return char ? char.toUpperCase() : '' })}console.log(camelCase('foo Bar')) // fooBarconsole.log(camelCase('foo-bar--')) // fooBarconsole.log(camelCase('foo_bar__')) // fooBar
- 将字符串的首字母转换为大写
请将 hello world 转换为 Hello World。
const capitalize = (string) => { const capitalizeRegex = /(?:^|\s+)\w/g return string.toLowerCase().replace(capitalizeRegex, (match) => match.toUpperCase())}console.log(capitalize('hello world')) // Hello Worldconsole.log(capitalize('hello WORLD')) // Hello World
- 依照3-4-4格局划分电话号码
let mobile = '18379836654' let mobileReg = /(?=(\d{4})+$)/g console.log(mobile.replace(mobileReg, '-')) // 183-7983-6654