Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

214
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda