关于javascript:前端正则表达式积累合集-1

42次阅读

共计 2074 个字符,预计需要花费 6 分钟才能阅读完成。

  1. 格式化货币 ( 仅转换小数点前的整数局部 )
    实现成果,遵循的准则:
  2. ==> 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'
  1. 实现 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, true
console.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,true
console.log(string)//   hello medium   
  1. 解析链接上的搜寻参数
// url https://qianlongo.github.io/vue-demos/dist/index.html?name=fatfish&age=100#/home

const 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
  1. 驼峰式字符串
    示例:
    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')) // fooBar
console.log(camelCase('foo-bar--')) // fooBar
console.log(camelCase('foo_bar__')) // fooBar
  1. 将字符串的首字母转换为大写
    请将 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 World
console.log(capitalize('hello WORLD')) // Hello World
  1. 依照 3 -4- 4 格局划分电话号码
let mobile = '18379836654' 
let mobileReg = /(?=(\d{4})+$)/g 

console.log(mobile.replace(mobileReg, '-')) // 183-7983-6654

正文完
 0