Reputation: 14074
I have an object, appointment, with a member, time:
function appointment(date_string){
this.time = ???;
}
When I get time from the database, it has trailing zeros. I'd like to remove them before assigning the value. For instance:
var a = new appointment("01/15/2015");
a.time = "01:33:00.000";
console.log(a.time) // should display 01:33:00, NOT 01:33:00.000
I tried
function appoinment(date_sting) {
this.time = function(){return (this.time).replace(".000","");};
}
but this does not work in the scenario.
Upvotes: 0
Views: 33
Reputation: 10849
As of ES 5.1 (ECMA 262) you can use the set
operator with Object.defineProperty
function appointment() {
Object.defineProperty(this, 'time', {
set: function (value) {
value = value + '';
this._time = value.replace(".000","");
},
get: function () {
return this._time;
}
});
}
Update
I came up with a better version that does not pollute this
' scope:
function appointment() {
var time;
Object.defineProperty(this, 'time', {
set: function (value) {
value = value + '';
time = value.replace(".000","");
},
get: function () {
return time;
}
});
}
Upvotes: 2
Reputation:
Regular expressions are your best friend. :)
a.time = "01:33:00.000".replace(/\.0+$/, "");
Also, the reason why "01:33:00.000".replace(".000") isn't doing anything is probably because you've forgotten to specify the second argument of the replace method: the string that replaces the first:
a.time = "01:33:00.000".replace(".000", "");
I recommend using a regex though, since it resolves the issue of having varying numbers of trailing zeroes. :)
EDIT: Okay, I see what you're trying to achieve now; you want something that dynamically parses the value upon assignment. In this situation, you'd want to use Object.defineProperty:
var Appointment = function(timeString){
var _time;
Object.defineProperty(this, "time", {
get: function(){ return _time; },
set: function(i){
_time = (i || "").replace(/\.0+$/, "");
}
});
this.time = timeString;
};
console.log(new Appointment("20/08/2015").time);
Fair warning though, using Object.defineProperty on native JavaScript objects isn't going to work on Internet Explorer 8. So this approach comes down to which browsers you're willing to support.
If supporting IE8 (and/or older) is a concern, I'd suggest resorting to using old-school get/set functions instead:
var Appointment = function(timeString){
var _time;
this.setTime = function(i){
_time = (i || "").replace(/\.0+$/, "");
};
this.getTime = function(i){
return _time;
};
this.setTime(timeString);
};
console.log(new Appointment("20/08/2015 1:33:00.000").getTime());
Upvotes: 0