JS live learning and using regular expressions

JS live learning and using regular expressions

JS RegExp Code Base

Record the regular tools used in some projects, and will continue to update...

If you don’t know much about the regular expressions in JS , you can refer to the regular expressions in JS.

1. String manipulation

Remove the spaces on both sides of the string trim

String.prototype.trim = function() {
  return this.replace(/(^\s+)\|(\s+$)/g,'')
}

HTML encoding, </> " &/equivalent character escape, avoid XSS attacks

function htmlEncode(str) {
  return str.replace(/[\<\>\"\'\&]/g, function(rs) {
    switch (rs) {
      case'<':
        return'<'
      case'>':
        return'>'
      case'&':
        return'&'
      case''':
        return'''
      case'"':
        return'"'
    }
  })
}

Find the most repeated characters

let str ='asss23sjdssskssa7lsssdkjsssdss'
const arr = str.split(/\s*/)//convert a string to an array
const str2 = arr.sort().join('')//Sort first, so that the result will put the same characters together, and then convert to a string
let value =''
let index = 0
str2.replace(/(\w)\1*/g, function($0, $1) {//match characters
  if (index <$0.length) {
    index = $0.length//index is the number of occurrences
    value = $1//value is the corresponding character
  }
})
console.log(`The most characters: $(value), the number of repetitions: $(index)`)//s 17

Number formatting, 1234567890 -> 1,234,567,890

The following is a simple analysis of the regular /\B(?=(\d{3})+(?!\d))/g:

  1. /\B(?=(\d{3})+(?!\d))/g: Regular matching non-word boundaries \B, the boundary must be followed by(\d{3})+(?!\d)
  2. (\d{3})+: Must be 1 or more of 3 consecutive numbers
  3. (?!\d): The 3 numbers in step 2 are not allowed to be followed by numbers
  4. (\d{3})+(?!\d): So the matching boundary must be followed by a number of 3*n (n>=1)

The final match to replace all boundaries ,to

const numFormat = str => str.replace(/\B(?=(\d(3))+(?!\d))/g,',')

Change the middle four digits of the phone number*

Replace the middle 4 digits of the phone number with *

const validateMobile = str =>/^[1][0-9]{10}$/.test(str) && str.replace(/(\d{3})(\d{4})(\d{ 4))/, (rs, $1, $2, $3) => `${$1}****${$3}`)

Take the query from the URL to an object

function getUrlParam(str) {
  const result = {}
  const valid =/(https?|ftp):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=% &:/~\+#]*[\w\-\@?^=%&/~\+#])?/.exec(str)
  if (!valid) return
  const [rs, $1, $2, $3] = valid
  $3.match(/[a-zA-Z_]+=[^=&?]*/g).forEach(val => val.replace(/^(\w+)=(\w*)$/, ( $0, $1, $2) => {
        result[$1] = $2
      })
  )
  return result
}

getUrlParam('https://www.baidu.com?name=jawil&age=23&d=')//{name: "jawil", age: "23", d: ""}

2. Verification

When used for authentication, it is usually required before and after the add ^, , $to\b match the entire string to be verified

Commonly used regular verification

function checkStr(str, type) {
  switch (type) {
    case'phone'://Mobile phone number
      return/^1\d{10}$/.test(str)
    case'tel'://landline
      return/^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str)
    case'card'://ID card
      return/^\d{15}|\d{18}$/.test(str)
    case'pwd'://The password starts with a letter, the length is between 6~18, and can only contain letters, numbers and underscores
      return/^[a-zA-Z]\w{5,17}$/.test(str)
    case'postal'://postal code
      return/[1-9]\d{5}(?!\d)/.test(str)
    case'QQ'://QQ number 5-11 digits
      return/^[1-9]\d{4,10}$/.test(str)
    case'email'://mailbox
      return/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str)
    case'money'://Amount (2 decimal places)
      return/^\d*(?:\.\d{0,2})?$/.test(str)
    case'URL'://URL
      return/(https?|ftp):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)
    case'IP'://IP
      return/((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[ 0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str)
    case'day'://31 days of a month 01-09 and 1~31
      return/^((0?[1-9])|(([12])[0-9])|30|31)$/.test(str)
    case'month'://12 months of the year 01-09 and 1-12
      return/^(0?[1-9]|1[0-2])$/.test(str)
    case'date'://date and time
      return/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d {2}):(\d{2}))$/.test(str) ||/^(\d{4})\-(\d{2})\-(\d{2})$/.test(str)
    case'integer'://integer positive integer or negative integer
      return/^-?\d+$/.test(str)
    case'decimal'://decimal
      return/^(-?\d+)(\.\d+)?$/.test(str)
    case'english'://English
      return/^[a-zA-Z]+$/.test(str)
    case'chinese'://Chinese
      return/^[\u4E00-\u9FA5]+$/.test(str)
    case'cname'://Chinese name with 2-4 Chinese characters
      return/^[\u4E00-\u9FA5]{2,4}$/.test(str)
    case'lower'://lowercase
      return/^[az]+$/.test(str)
    case'upper'://uppercase
      return/^[AZ]+$/.test(str)
    case'HTML'://HTML markup
      return/<("[^"]*"|'[^']*'|[^'">])*>/.test(str)
    default:
      throw new Error('Check error in function checkStr')
  }
}

Verify if it is a legal URL

function validateURL(textval) {
  const urlregex =/^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@) *((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[ 0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA- Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero| coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$ #=~_-]+))*$/
  return urlregex.test(textval)
}

Most of the posts on the Internet are of different depths, and even some are inconsistent. The articles below are summaries of the learning process. If you find errors, please leave a message to point out~

Reference: The way to advance JavaScript regularity-live learning and magical regular expression js regular verification method javascript summary (RegExp article)

Reference: https://cloud.tencent.com/developer/article/1356666 JS Live Learning and Use Regular Expressions-Cloud + Community-Tencent Cloud