1

Javascript / Vue n00b. Want to write a filter that formats a value that is a 1 - 3 digit number. I want a 1 digit number to change to '#00X', 2 digit number to '#0XX' and 3 digit to '#XXX'. So far I have this:

//Vue Filter

Vue.filter('number_filter', function (value){
  if(value.length === 1){
    value = value.toString()
    return '#00' + value;
  }else if(value.length === 2){
    value = value.toString()
    return '#0'+ value;
  }else{
    value = value.toString()
    return '#' + value;
  }
});

The filter will take 'X' and return '#X' because it doesn't break when the first condition is met. What can I do?

5 Answers5

1

You can simplify it:

Vue.filter('number_filter', function (value){

  value = value.toString()
 
  if(value.length === 1){
    return '#00' + value;
  }
  if(value.length === 2){
    return '#0'+ value;
  }
    return '#' + value;
  
});
Raffobaffo
  • 2,806
  • 9
  • 22
1

For example:

 Vue.filter('number_filter', function (value){
     return "#"+"0".repeat(3 - value.length)+value.toString();
 });
Oyeme
  • 11,088
  • 4
  • 42
  • 65
1

Here's a post regarding how to get the number of digits.

Also, based on your question, unless there's an overlying condition that stops someone from entering a number that contains more than 3 digits, then you're output could end being something like "#3051". You would need another else-if to check for number of digits === 3.

chataolauj
  • 99
  • 1
  • 15
1

You can use String.prototype.padStart() and avoid the if/else:

Vue.filter('number_filter', function (value){
    return '#' + value.toString().padStart(3, '0');
});

In your original code, the value is of Number type and you are checking on length property on Number which will always be undefined, you need to convert it to string first and then check on value:

Vue.filter('number_filter', function (value){
  value = value.toString();
  if(value.length === 1) {
    return '#00' + value;
  } else if(value.length === 2) {
    return '#0'+ value;
  } else {
    return '#' + value;
  }
});
Muhammad Talha Akbar
  • 9,952
  • 6
  • 38
  • 62
-2

The String method padStart will do for your requirement. It will add 0 for 2 digits and rest will be returned as it is.

Vue.filter('number_filter', function (value){
 return '#' + value.padStart(3, 0)
});
Stark Buttowski
  • 1,799
  • 2
  • 10
  • 21