0

I can do each of them using regex, but I'm unsure how to combine them into a single regex to achieve both.

For example, this is what I'd like to happen:

HELLO_THERE -> Hello There

Found this, but it does the opposite of what I want, it lowercases the first, when i'd like it to lower case everything AFTER the first:

function changeStr(string){
  return string.replace(/(?:_| |\b)(\w)/g, function($1){return $1.toLowerCase().replace('_',' ');});
}

changeStr(HELLO_THERE) -> hELLO tHERE

Noob
  • 754
  • 3
  • 10
  • 27

1 Answers1

1

Not in a single regex, no. But you can make use of an anonymous function for the replacement:

function changeStr( string ){
   
    // Match underscores or the alphabet
    return string.replace(/[A-Za-z]+|_/g, function( match ){
        if( match === '_' ){
            // If we have an underscore then return a space
           return ' ';
        }
        else{
            // For everything else we capitalize the first char and lowercase the rest
            return match.substr(0, 1).toUpperCase()+match.substr(1).toLowerCase();
        }
    });
}

console.log( changeStr( 'HELLO_THERE_my_frIenD_MonkeyZeus' ) );
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77