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

114
Views
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 answers
Answer question

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 Report

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 Report

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 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!