LoveAndCoding
LoveAndCoding

Reputation: 7947

With matched regex character, how can I get its uppercase equivalent?

The basic premise is I want to find a character following another and then replace that with its uppercase equivalent. I'm looking for a more elegant solution than indexOf and a for loop. I've got this far:

'this-is-my-string'.replace(/\-(\w)/,'$1')

which gives me thisismystring but I want thisIsMyString. Anything I can do to change $1 into its uppercase equivalent?

Upvotes: 2

Views: 91

Answers (2)

zamnuts
zamnuts

Reputation: 9592

I would suggest using James Robert's toCamel string method.

String.prototype.toCamel = function(){
    return this.replace(/(\-[a-z])/g, function($1){return $1.toUpperCase().replace('-','');});
};

Then call it like:

'this-is-my-string'.replace(/\-(\w)/,'$1').toCamel();

Upvotes: 3

Trevor
Trevor

Reputation: 9578

You can use give replace a function as the second argument and whatever it returns will be used:

'this-is-my-string'.replace(/\-(\w)/g, function(_, letter){
    return letter.toUpperCase();
});

Upvotes: 3

Related Questions