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?

1
  • Use String(value).length Commented Jul 7, 2020 at 15:44

5 Answers 5

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;
  }
});
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

1

For example:

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.