Anonymously Replace string with Regex with simple example

# 单元源 (6 years ago)

No no no, the regex provided here may be included from some where out of your control, all you need to do is replacing the matched part in input string. This is may be useful when you need to do something like this:

const template1 = { data: 'USA#1', regex: /(\w+)/(\d+)/ } const template2 = { data: 'Mongo$6', regex: /(\w+)/(\d+)/ } const template3 = { data: 'I am a Javascript Coder age 28', regex: /I am a (\w+) Coder age (\d+)/ }

const handler = (template, family, version) => { // the replacers here may be more complex, it is just a simple example, nothing more. return template.data.replace(template.regex, x => family, x => version); }

// INPUT: template1, CHINA 99 OUTPUT: CHINA#99 // INPUT: template3, Golang 20 OUTPUT: I am a Golang Coder age 20

Here I use template 1/2/3, it may be some alias instead of real template. For example we may make a map of template, then I just need hander(alias, family, version) to generate some meaningful string. Of cause you could write it in some other way, I just want to show what can this feature do.

# 单元源 (6 years ago)

There is some errors by the way, missing # in template1.regex and $ in template2.regex, sorry for that.