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

128
Views
Camel case to Title case doesnt work for the first letter

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");
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.
about 4 years ago · Juan Pablo Isaza Report

0

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

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!