Krishan
Krishan

Reputation: 33

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?

Upvotes: 1

Views: 488

Answers (2)

The fourth bird
The fourth bird

Reputation: 163287

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);

Upvotes: 0

Ryszard Czech
Ryszard Czech

Reputation: 18611

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.

Upvotes: 1

Related Questions