Regular sum callback function of replace

Time:2021-4-18

Common usage

String. Replace (‘replaced character ‘, replaced character)
For example:

'abcabcabc'.replace('a', 'h') // hbcabcabc

Regular expression substitution

'abcabcabc'.replace(/[a]+/g, 'h') // hbchbchbc

Callback function

'abcabcabc'.replace(/[a]+/g, () => {
    return 'h'
}) // hbchbchbc

//1. / [(a)] + / g () represents packet capture
//2. There are four callback parameters: match item, group capture content, capture item location and original string

Complex example: if there is a requirement for users to configure a text template, the data will be filled according to the content returned by the interface during rendering.

//Back end return data
var res = {
    year: '2021',
    month: '03',
    day: '17',
    a: 10,
    b: 9
}
//Text template
Var STR = "${month} day of ${year} year, XXX system is in the state of ${a > b?'normal ':'abnormal'}"

//Replace characters such as ${...}
str.replace(/${([^{}]+)}/g, (item, prop)=>{
    //For alphabetic variables, replace them with real data
    //Item: matching string
    //Prop: the attribute string that needs to be recognized by group capture
    var result = prop.replace(/([a-zA-Z]+)/g, (i, p)=>{
        //Property with actual data
        return res[p]
    })
    //It may be an expression, and eval is used to evaluate the result
    return  eval(result)
})
//"On March 17, 2021, XXX system is in normal state"

Recommended Today

Deeply analyze the principle and practice of RSA key

1、 Preface After experiencing many dark moments in life, when you read this article, you will regret and even be angry: why didn’t you write this article earlier?! Your darkest moments include: 1. Your project needs to be connected with the bank, and the other party needs you to provide an encryption certificate. You have […]