notmynamelastname
notmynamelastname

Reputation: 105

Stop vue filter / javascript when condition is met

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?

Upvotes: 1

Views: 352

Answers (5)

Oyeme
Oyeme

Reputation: 11235

For example:

 Vue.filter('number_filter', function (value){
     return "#"+"0".repeat(3 - value.length)+value.toString();
 });

Upvotes: 1

Talha Akbar
Talha Akbar

Reputation: 10040

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;
  }
});

Upvotes: 1

Stark Buttowski
Stark Buttowski

Reputation: 1849

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)
});

Upvotes: -2

chataolauj
chataolauj

Reputation: 119

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.

Upvotes: 1

Raffobaffo
Raffobaffo

Reputation: 2856

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;
  
});

Upvotes: 1

Related Questions