I am trying to replace a string which has place holders with values in an object
For Example:
let contentString = `
I, <<firstName>> <<lastName>>, born on <<DOB>> of <<flatNumber>> , <<houseNumber>>
`;
let data = {
firstName: 'test_firstName',
lastName: 'test_lastName',
DOB: '10-12-1987',
flatNumber: '3',
houseNumber: '8'
};
function createTemplate(contentString, data) {
let pattern = /<<(\w*?)>>/gm;
while (matches = pattern.exec(contentString)) {
contentString.replace(matches[1], function replacer(match) {
console.log(match);
//contentString = contentString.replace(match, data[match]);
});
}
console.log(contentString);
}
createTemplate(contentString, data);
The console.log function in the replacer callback function extracts all the values such as firstName,lastName,DOB,flatNumber and houseNumber.
However, once i uncomment the next line of code which is string replace although the firstName is replaced by the value the <<lastName>>
is never replaced.
Whereas if i change the contentString to something like
let contentString = `
I, <<firstName>> asnasas <<lastName>>, born on <<DOB>> of <<flatNumber>> , <<houseNumber>>
`;
inserting some text between the <<firstName>>
and <<lastName>>
it works.
Can anyone please guide is towards my mistake. Thank you in advance.