silkfire
silkfire

Reputation: 25935

JavaScript convert boolean to string according to PHP's practice

Is there some way to convert a boolean to string in the same way as PHP does it?

So that false becomes '' (empty string) and true becomes 1.

As of right now, true.toString() becomes "true" and false.toString() becomes "false", not what I want.

Upvotes: 0

Views: 130

Answers (1)

Thorben Croisé
Thorben Croisé

Reputation: 12870

Boolean.prototype.toPHPString = function() { 
  return this ? '1' : '' 
};

will give you

true.toPHPString() // => '1'
false.toPHPString() // => ''
(1 == 1).toPHPString() // => '1'

Upvotes: 2

Related Questions