Preserve Spaces mentioned in String format

Viewed 187
const person = {
  name: 'John',
  middle: 'S',
  last: 'Smith'
}

const format = "{​​​​​​​ name }​​​​​​​ {​​​​​​​​    ​​​​​​middle }​​​​​​​​​​​​​​ {​​​​​​​​​​​​​​ last}​​​​​​​​​​​​​";

The curly braces acts like a placeholder for dynamic values. i:e {name} will get replaced with John, {middle} with S.

The issue I'm facing is with preserving the spaces in between the format. i:e if there exist two spaces in the {name} {middle}, then the output should be John S.

I'm replacing the placeholder with actual values and joining it with the single space, but it would be static always.

const person = {
  name: 'John',
  middle: 'S',
  last: 'Smith'
}

const format = "{​​​​​​​ name }​​​​​​​ {​​​​​​​​    ​​​​​​ middle }​​​​​​​​​​​​​​ {​​​​​​​​​​​​​​ last}​​​​​​​​​​​​​";

function formatStr(obj, format) {
  return format.match(/\b\w+\b/g).map((s) => person[s]).join(' ');
}

console.log(formatStr(person, format));

Help would be really appreciated :)

1 Answers

You can use a .replace operation, matching the substrings between {...} with one word inside and replacing with the values from the person object if they exist.

const person = {
  name: 'John',
  middle: 'S',
  last: 'Smith'
}

const format = "{​​​​​​​ name }​​​​​​​ {​​​​​​​​    ​​​​​​ middle }​​​​​​​​​​​​​​ {​​​​​​​​​​​​​​ last}​​​​​​​​​​​​​";

function formatStr(obj, format) {
  return format.replace(/\{[^\w{}]*(\w+)[^\w{}]*}/g, (x,y) => person[y] ?? x);
}

console.log(formatStr(person, format));

This will keep all spaces and other chars in between } and {.

See the regex demo. Details:

  • \{ - a { char
  • [^\w{}]* - zero or more non-word chars other than { and }
  • (\w+) - Group 1: one or more word chars
  • [^\w{}]* - zero or more non-word chars other than { and }
  • } - a } char.
Related