Camel case to Title case doesnt work for the first letter

Viewed 60

I need to make the given string to title case, no matter whether the input is lower or upper case

memberships 1 - contactGroupMembership - contactGroupId should return Memberships 1 - Contact Group Membership - Contact Group Id

memberships1-contactGroupMembership-contactGroupId should return Memberships 1 - Contact Group Membership - Contact Group Id

I have tried with

str.replace(/([A-Z]+)/g, " $1").replace(/([A-Z][a-z])/g, " $1");
2 Answers

You may use this 2 step solution for your case:

input = ['memberships 1 - contactGroupMembership - contactGroupId', 'memberships1-contactGroupMembership-contactGroupId'];

const re1 = /\B(?:[A-Z]|\d)|\b-\b|(?<=-)[a-z]/g;
const re2 = /\b[a-z]/g;

var repl = [];
input.forEach(str => {
  repl.push(str
    .replace(re1, ' $&')
    .replace(re2, m => m.toUpperCase())
  );
});

console.log(repl);

Explanation:

  • In the first .replace we insert space at desired places using first regex:

    \B(?:[A-Z]|\d)|\b-\b|(?<=-)[a-z]
    

This matches a non-word boundary followed by upper case letter or digit or a - that is surrounded with word boundaries on both sides or a lower case letter that must be preceded with a -. RegEx Demo 1

  • In the second step we match lower case letter after a word boundary and make it upper case.

Very specific to this user case, but you can also use a replacer function to uppercase either the first character of a word or the first capital: str.replace(/(\b[a-z])|([A-Z]+)/g, (m,p1,p2)=> (p1 ? '' : ' ') + (p1 || p2).toUpperCase());

working: either beginning of the word (used in p1) or the first capital (p2) is found. The replacer function uppercases that match, and adds the extra space only if it is not a p1 match

Demo:

let str = 'memberships 1 - contactGroupMembership - contactGroupId';

str = str.replace(/(\b[a-z])|([A-Z]+)/g, (m,p1,p2)=> (p1 ? '' : ' ') + (p1  || p2).toUpperCase());

console.log(str);

Related