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

213
Visualizações
Using regex for apostrophe

I am using this function

function capitalizeAllWords(str: string) {
  return str.replace(/\b\w/s, letter => letter.toUpperCase());
  }

Current result: Men's apparel

Required result: Men's Apparel

how to achieve this?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Use

function capitalizeAllWords(str: string) {
  return str.replace(/(?<![\w'])\w/g, letter => letter.toUpperCase());
}

EXPLANATION

--------------------------------------------------------------------------------
  (?<!                     look behind to see if there is not:
--------------------------------------------------------------------------------
    [\w']                    any character of: word characters (a-z,
                             A-Z, 0-9, _), '''
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  \w                       word characters (a-z, A-Z, 0-9, _)

Mind the g flag to replace all matches, not s.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use the callback of the replace method.

function capitalizeAllWords(str: string) {
    return str.replace(/'[a-z]|\b([a-z])/g, (m, g1) => g1 ? g1.toUpperCase() : m);
}

Capture what you want to uppercase in group 1 (denoted by g1 in the example code), and match what you want to leave untouched (denoted by m in the example code)

'[a-z]|\b([a-z])

Explanation

  • '[a-z] Match ' and a char a-z
  • | Or
  • \b([a-z]) A word boundary \b to prevent a partial match, and capture a char a-z in group 1

Regex demo

const regex = /'[a-z]|\b([a-z])/g;
const str = "Men's apparel $test";
let res = str.replace(regex, (m, g1) => g1 ? g1.toUpperCase() : m);
console.log(res);

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