Piotr Berebecki Piotr Berebecki - 1 year ago 37
Javascript Question

Using regex replace() method to remove delimiters and capitalise first letters in one step

I've developed the following function (also available in this codepen: http://codepen.io/PiotrBerebecki/pen/RRKjex) when trying to remove all underscore delimiters and convert the first letters to upper case.



as an input string, the function should return

Working JS code:

function capitaliseFirst(str) {
var firstCapital = str.replace(/[a-z]+/g, x => x[0].toUpperCase() + x.slice(1));
return firstCapital.replace(/_/g, '')

console.log( capitaliseFirst('this_is_some_text') ); // returns ThisIsSomeText

The function above achieves the desired objective, however I would like to refactor it so that only one
method is required. At the moment I'm stuck at the code below. Would you know how this could be completed?

Not working (yet) JS code:

function capitaliseFirst2(str) {
return str.replace(/(?:_)?([a-z])/g, '$1')

console.log( capitaliseFirst2('some_other_text') ); // should return SomeOtherText

Answer Source

Here's one way:

function capitaliseFirst2(str) {
    return str.replace(/(?:_+|^)(.)/g, (m0, m1) => m1.toUpperCase());

We match and capitalize every character that comes after 1 or more underscores or the beginning of the string.