I have an input line and a replacement object. Now you need to find the appearance of the text (the key of the object), divided =, and want to replace it with values. but could not find a solution. Here is my snippet and code as follows.
var replacer = function(tpl, data) {
console.log('input==>', tpl);
for(var key in data) {
var re = new RegExp(key + '=(.*)', 'g');
tpl = tpl.replace(re, function(match, p1, offset, string) {
console.log('Replace=>', arguments);
return p1;
});
console.log('output==>', tpl);
}
console.log('final output==>', tpl);
};
var text = 'alpha=1\nbeta=2\nage=12\ncolor=green';
var result = replacer(text, { age: 15, color: 'red' });
Run codeHide resultinput line: 'alpha=1\nbeta=2\nage=12\ncolor=green'
placeholder object: { age: 15, color: 'red' }
desired output: 'alpha=1\nbeta=2\nage=15\ncolor=red'
Test 1
use return p1;, then the end result was ==>'alpha=1\nbeta=2\n12\ngreen'
Test 2
use return data[key];than final output ==>'alpha=\nbeta=2\n15\nred'
So what will be the right step to achieve the result of desire?
source
share