String interpolation. Find the objects prop that matches the string inside [...] and replace with the value of the prop

Viewed 276

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);
1 Answers

You could use the regex

(?<!\[)\[([^[\]]*)](?!\])

Regex demo

This will get all the strings with [] which are not preceded by a [ and followed by a ]. The ([^[\]]*) part will get the string inside [] to a capturing group. You can use the second parameter from the replacer function to access this and get the value from the object.

Replace the matched string with the property from the object

function interpolate (string, obj) {
   return string.replace(/(?<!\[)\[([^[\]]*)](?!\])/g, (m, p1) => obj[p1] ?? '')
}

const str = 'Replace name: [name] but not [[author]]. Replace this with author: [author]';

console.log(
  interpolate(str, { name: 'John', author: 'John & John'})
)

console.log(
  interpolate(str, { name: 'Jill', author: 'Jk Jowling' })
)

Related