Javascript text input on input text change format to two decimal places

Hi I have the below code which sanitises text entered in input text.

let formattedText = text
        .replace(/[^0-9.]/g, "") // remove chars except number, point.
        .replace(/(..*)./g, "$1") // remove multiple points.
        .replace(/^0+(d)/gm, "$1"); // remove multiple leading zeros.

I am stuck at a scenario where i want to restrict to two decimal places without using toFixed(2)

for example user should enter 100.203

Answer

You can change your second regex to this

.replace(/(.d{1,2}).*/g, "$1") // remove multiple points.

(.d{1,2}).*/
  • (.d{1,2}) – Match . followed by 1 or 2 digits
  • .* – Match anything except new line zero or more time

let formattedText = (text) => text
  .replace(/[^0-9.]/g, "")
  .replace(/.{2,}/g,'.')
  .replace(/^0*([^0]d*.d{1,2}).*/g, "$1")
  
  
console.log(formattedText('abcb123.25252.235252abdbch'))
console.log(formattedText('abcb123.2.2gvsgvs'))
console.log(formattedText('abcbcbbc123'))
console.log(formattedText('123.avsvs.123'))
console.log(formattedText('avsvs.1234'))
console.log(formattedText('avsvs1234'))

  .replace(/.{2,}/g,'.')

This replaces consecutive . periods if there are any, i.e abc123.aba.123 here after first replace the string will become 123..123 so to make it a valid number we need to replace .. with single .


.replace(/^0*([^0]d*.d{1,2}).*/g, "$1")

This simply combines the combine yours regex which are used to remove the leading 0’s and multiple decimals, this regex means

  • ^0* – Match 0 zero or more time at start of string
  • ([^0]d*.d{1,2}) – Match non zero digit, followed by any number of digit followed by . followed by one or two digit
  • .* – Match anything except new line

Leave a Reply

Your email address will not be published. Required fields are marked *