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
Complex string manipulation by JavaScript regexp

I am generating some meaningful name with the following rule in a JavaScript/Node JS program:

Input: "tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId"

Expected output: "TenancyAccountAccountPublicIdWorkspaceWorkspacePublicIdRemove-userUserPublicId"

Rules:

  1. replace any character with zero or more underscore to the non-underscored uppercase Example:x | __*x => X
  2. If exists remove last _

This is what is tried so far, looking for better alternatives, if any:

const convertBetterString = (input) => {
    const finalString = [];
    if (input && input.includes('_')) {
        const inputStringSeparation = input.split('_');
        if (inputStringSeparation.length > 1) {
            if (inputStringSeparation[inputStringSeparation.length - 1] === '') {
                inputStringSeparation.splice(inputStringSeparation.length - 1, 1);
            }
            inputStringSeparation.forEach((val, index) => {
                if (val === '' && inputStringSeparation[index + 1]) {
                    const actualString = inputStringSeparation[index + 1];
                    const formattedString = actualString.charAt(0).toUpperCase() + actualString.slice(1);
                    finalString.push(formattedString);
                }
            });
            return finalString.length > 0 ? finalString.join('') : inputStringSeparation.join('');
        } else {
            return input.charAt(0).toUpperCase() + input.slice(1);
        }
    } else {
        return input;
    }
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Split and slice

const capitalise = str => str.slice(0,1).toUpperCase() + str.slice(1); // you can add more tests

const str = "tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId"
const newStr = str.split(/_+/)
  .map(word => capitalise(word))
  .join("")
console.log(newStr)

Regexp with optional chaining

const str = "tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId_"

const newStr = str.replace(/(?:_+|^)(\w)?/g, (_,letter) => letter?.toUpperCase() ?? "")

console.log(newStr)

Explanation

(?:_+|^) non-capturing the underscore OR start
(\w)? followed by 0 or 1 letter to be captured
(_,letter) => letter?.toUpperCase() ?? "") ignore the match and uppercase the letter if found, that ignores trailing underscores too

about 4 years ago · Juan Pablo Isaza Report

0

You can use

const str = "tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId__";
const newStr = str
    .replace(/(?:^|_)_*([^\s_])|_+$/g, (_, x) => x ? x.toUpperCase() : '')
console.log(newStr);

The /(?:^|_)_*([^\s_])|_+$/g regex matches all occurrences of

  • (?:^|_) - start of string or _
  • _* - zero or more underscores
  • ([^\s_]) - Group 1: any char other than whitespace and _.
  • | - or
  • _+$ - one or more _s at the end of string.

The (_, x) => x ? x.toUpperCase() : '' replacement remove all the underscores (even if they are at the end of string) and turns the Group 1 value (x) to upper case.

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!