I am working on a function that finds the objects prop that matches the string inside [...] and replaces with the value of the prop.. it also has to ignore any strings inside of [[...]] and remove the outer square brackets
For example
interpolate('Hello [name] [[author]]', {name: 'foo', author: 'bar'})
Would result in 'Hello foo [author]'
Here is my code so far
const person1 = { name: 'John', author: 'John & John'};
const person2 = { name: 'Jill', author: 'Jk Jowling' };
const person3 = { name: 'Jack', author: 'Wacko Jacko'};
const str1 = 'Hello [name] [[author]]';
// Find the objects prop that matches the string inside [...] and replace with the value of the prop
// Ignore the values inside double brackets [[...]]
const interpolate = (string, obj) => {
// Throw errors if incorrect arguments are passed in
if (!string || typeof string !== 'string') {
throw new Error(`"string" is required`);
}
if (!obj || typeof obj !== 'object') {
throw new Error(`"object" is required`);
}
Object.keys(obj).map((value) => {
string
.split(' ')
.indexOf(`[${value}]`) === 1 || string.indexOf(`[[${value}]]`) === -1
? console.log(string.replaceAll(`[${value}]`, obj[value]))
: console.log(`One or more unidentifiers found in String: ${string}`)
})
// Working better but still need to work on conditionals
// Removed RegEx
// Used replaceAll to target multiple [string]
};
interpolate(str1, person1);
interpolate(str1, person2);
interpolate(str1, person3);