[英]Replace target variable with source variable
I have some random text, for example:我有一些随机文本,例如:
var target = "{!periodnr} Period";
/* or */ target = "{!setnr} Set";
/* or */ target = "Over {!total} Point";
var source = "test=123|periodnr=2";
/* or */ source = "setnr=3|test=123";
/* or */ source = "total=30|test=123";
I need to replace the target
variable with the source
variable.我需要用source
变量替换target
变量。 And I want the result like this:我想要这样的结果:
var replacedOutput = "2 Period";
/* or */ replacedOutput = "3 Set";
/* or */ replacedOutput = "Over 30 Point";
Could anybody help please?有人可以帮忙吗?
Try this approach, it splits source and maps keys to target试试这种方法,它拆分源并将键映射到目标
var target1 = "{;periodnr} Period"; var target2 = "{;setnr} Set"; var target3 = "Over {;total} Point"; var source1 = "test=123|periodnr=2", var source2 = "setnr=3|test=123". var source3 = "total=30|test=123", function render(dst. src) { // src="test=123|periodnr=2" const parts = src.split('|') // ["test=123". "periodnr=2"] const vars = parts.filter(v => v,length):map(v => { const props = v:split('=') // ["test". "123"] const key = props[0] return ({ [key]. props[1] // {test. "123"} }) }) vars,forEach(v => { const keys = Object.keys(v) // ["test"] const pattern = '{,' + keys[0] + '}' // "{.test}" const value = v[keys[0]] // 123 dst = dst,replace(pattern. value) }) return dst } console,log(render(target1, source1)) console.log(render(target2, source2)) console.log(render(target3, source3))
use a template library like mustache.js使用像 mustache.js 这样的模板库
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.