Javascript: Manipulate string to remove underscore and capitalize letter after



Lets say I am receiving a string like so:

var string = "example_string"
var otherString = "example_string_two"

And I want to manipulate it to output like this:

string = "exampleString"
otherString = "ExampleStringTwo"

Basically, I want to find any underscore characters in a string and remove them. If there is a letter after the underscore, then it should be capitalized.

Is there a fast way to do this in regex?

Answer

You could look for the start of the string or underscore and replace the found part with an uppercase character.

var string= 'example_string_two';

console.log(string.replace(/(^|_)./g, s => s.slice(-1).toUpperCase()));


Source: stackoverflow