2

I have a price input like this:

<Input
   keyboardType={"decimal-pad"}
   inputStyle={{color: "#EDF5E1"}}
   value={this.state.price.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.")}
   onChangeText={(newPrice)=>this.setState({price: newPrice.toString().replace(".", ""})}
/>

My aim is to add dots to every 3 digits while the user is typing! like this(12.443.355) this piece of code price.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.")} works fine, but as user modifies the number, it messes up!

note that my problem differs from JavaScript; How to set dot after three digits?, I'm able to add dots, but it messes up when the user modifies it.

Reza Shoja
  • 887
  • 2
  • 11
  • 24
  • 1
    I found a NPM library which could help to you to solve it. Please check this out https://www.npmjs.com/package/react-number-format – marcode_ely Feb 13 '19 at 14:37
  • Is this, by any chance, supposed to be for entering an IP address? Because there may be a better way. There are likely IP address components available. – Wyck Feb 13 '19 at 14:44
  • This may just be typos, so only commenting for now. First, your value set needs to use `this.state.price`, not just `price`. Second, your `onChangeText` handler is inconsistent. Change the arrow-function parameter name from `price` to avoid collision with the state name, and remove the superfluous `.toString()` – Marc L. Feb 13 '19 at 14:45
  • 1
    `price: to.toString()` looks like a typo. did you mean `price: price.toString()`? – Wyck Feb 13 '19 at 14:46

1 Answers1

3

I don't know what "to" in to.toString().replace(".", "") is but I'm sure you should use to.toString().replace(/\./g, "") instead of replace(".", "") because replace only replaces the first occurance in the string by default.

Eddie Cooro
  • 1,676
  • 14
  • 18
  • I'm sorry, "to" is a typo, it's "price", but your solution doesn't work I get this error: "price.toString(...).replaceAll is not a function". looks like 'replaceAll' function doesn't exist at all! – Reza Shoja Feb 13 '19 at 15:06
  • @BlueTurtle I'm so sorry, my bad... I will edit my answer. – Eddie Cooro Feb 13 '19 at 15:49