Home > Software design >  Complex string manipulation by JavaScript regexp
Complex string manipulation by JavaScript regexp

Time:12-17

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related