Monday, June 3, 2013

The split/join way to "replace all" in JavaScript.

var foo = bar.replace('baz','qux'); is painful because only the first instance of baz within bar is going to be replaced with qux. If bar contains "this foo bar stuff is fubared" then foo will end up reading "this foo qux stuff is fubared" and not "this foo qux stuff is fuquxed" which might be desired. A good way to replace ALL instances on the left side with a right side counterpart looks like this:

function nameDummyDomain() {
   var dummyDomain = "temp" + new Date();
   dummyDomain = dummyDomain.split("(")[0];
   dummyDomain = dummyDomain.split(' ').join('');
   dummyDomain = dummyDomain.split(':').join('');
   dummyDomain = dummyDomain.split('-').join('');
   return dummyDomain;
}

No comments:

Post a Comment