How to replace inside a line above a loop of a placeholder object?

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 result

input 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?

+4
source share
3 answers

, , data[key] undefined. , - , , , , :

var replacer = function(tpl, data) {
  for(var key in data) {
    var re = new RegExp(key + '=.*', 'g');
    tpl = tpl.replace(re, data[key] ? key + '=' + data[key] : '$&');
  }
  return tpl;
};

var text = 'alpha=1\nbeta=2\nage=12\ncolor=green';
var result = replacer(text, { age: 15, color: 'red' });
console.log(result);
Hide result

: age mage,

var re = new RegExp('\\b' + key + '=.*', 'g');
                     ^^^^  
+2

-,

return key+'='+data[key];

tpl

+2

You can also try

var replacer = function(tpl, data) {
  console.log('input==>', tpl);
  for(var key in data) {
    var re = new RegExp(key + '=(.*)', 'g');
    tpl = tpl.replace(re, key+'='+data[key]);
  }
   console.log('final output==>', tpl);
};

var text = 'alpha=1\nbeta=2\nage=12\ncolor=green';

var result = replacer(text, { age: 15, color: 'red' });
+1
source

Source: https://habr.com/ru/post/1663750/


All Articles