Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

214
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda