williamsandonz
williamsandonz

Reputation: 16430

A nicer way to do multiple replaces?

var type = event.type.replace('page', 'Page').replace('init', 'Init').replace('before', 'Before').replace('show', 'Show').replace('hide', 'Hide');

Can anyone think of a nicer way to do this?

Upvotes: 0

Views: 70

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

What you have is fine. There is another way to do it:

var type = event.type.replace(/page|init|before|show|hide/g, function(m) {
    return m.substring(0,1).toUpperCase() + m.substring(1);
});

Live example

Or in the general case (not limited to the set of strings shown):

var type = event.type.replace(/(\S)(\S+)/g, function(m, c1, c2) {
    return c1.toUpperCase() + (c2 ? c2 : "");
});

Live example

Upvotes: 2

Rob W
Rob W

Reputation: 349042

You can use a RegExp with .replace(), passing a function as second argument (=pure JavaScript):

var type = event.type.replace(/page|init|before|show|hide/, function(s) {
    return s.charAt(0).toUpperCase() + s.slice(1);
});

Upvotes: 7

Related Questions