3

Here I have written a code in vue.js. This code is for while user enters a number in a price field then after three digit comma "," will prompt dynamically. SO this functionality is expected and it is working fine but the issue is while we try to enter a dot '.' manually it is not allowing us enter the dot. SO in this script i want to allow the user to enter a dot '.' manually. So please help me to solve this issue.

<div id="vue">
  <input type="text" v-model="price" />
</div>
<script>
new Vue({
  el: '#vue',
  data: {
    price: 0
  },
  watch: {
    price: function(newValue) {
      const result = newValue.replace(/\D/g, "")
        .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      Vue.nextTick(() => this.price = result);
    }
  }
});
</script>

1 Answer 1

1

You are replacing all non-digit characters so exclude . from that. You can use negated character class.

newValue.replace(/[^.\d]/g, "")

Final code:

  watch: {
    price: function(newValue) {
      const result = newValue.replace(/[^.\d]/g, "")
        .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      Vue.nextTick(() => this.price = result);
    }
  }

UPDATE : And in the other replace you have to exclude comma in decimal part for that you can use negative look-behind assertion.

.replace(/\B(?<!\.\d+)(?=(\d{3})+(?!\d))/g, ",");

Final code:

  watch: {
    price: function(newValue) {
      const result = newValue.replace(/[^.\d]/g, "")
        .replace(/\B(?<!\.\d+)(?=(\d{3})+(?!\d))/g, ",");
      Vue.nextTick(() => this.price = result);
    }
  }
Sign up to request clarification or add additional context in comments.

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.