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

120
Vistas
Regex for last capital letter in string

I have a regular expression implemented in javascript that checks for all capital letters in a string:

.match(/[A-Z]+[^A-Z]*|[^A-Z]+/g)

then adds a space by .join(" ")

–

How can I write a regular expression that finds only the last capital letter instead, then joins a space before that letter? Thanks for your help.

—

Sample Input: "HelloMyNameIsNick"

Ideal Output: "HelloMyNameIs Nick"

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

To add a space before the last uppercase letter, greedily match all followed by a single uppercase letter:

"ABCabcABC".replace(/(.*)([A-Z])/, "$1 $2")
"ABCabcAB C"

To add a space before the last uppercase letter for each uppercase sequence, match an uppercase letter that is not followed by another uppercase letter:

"ABCabcAB".replaceAll(/([A-Z](?![A-Z]))/g, " $1")
"AB CabcA B"
about 4 years ago · Juan Pablo Isaza Denunciar

0

Update

'HelloMyNameIsNick'.replace(/([^ \n])([A-Z][^A-Z]*$)/gm, '$1 $2')

Test cases:

console.log(`
HelloMyNameIsNick
Hello
 Hello
HELLO
HellO
HeLLo
Hello Test
HELLO TEST
hello test
HELLO 1$@(😎-.aa
HELLO 1$@(😎-.Aa
`.replace(/([^ \n])([A-Z][^A-Z]*$)/gm, '$1 $2'))

Check out test cases which are handled properly:

Hello
 Hello 
Hello Test

Old answer that only finds last uppercase

What you are looking for is

/[A-Z](?!.*[A-Z].*)/gm

Playground with tests

It finds only the last capital letter.

If you want to find last letter in whole text instead on each line you can replace m (multiline) to s (single line):

/[A-Z](?!.*[A-Z].*)/gs

Playground with tests

*Note / /s flag may not be supported in all browsers.

(?!ABC) refers to negative lookahead. It checks conditions in expression but not includes them in the final result. More info

about 4 years ago · Juan Pablo Isaza Denunciar

0

Use a non-greedy quantifier:

/[A-Za-z]*?([A-Z])[^A-Z]*/

I suggest you add beginning and end anchors to make sure that you are matching the entire string, otherwise the pattern will segment strings:

/^[A-Za-z]*?([A-Z])[^A-Z]*$/

Try it out here: https://regex101.com/r/h9Acm6/1

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