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

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

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 Report

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