Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
Preserve Spaces mentioned in String format
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 :)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!