'Regex - Remove special characters but retain negative numbers

I'm building a Number Stepper component in React which needs to support integers (both positive and negative) and decimal numbers. I want to only hold the numeric part of any possible value in state in order for the arithmetic methods to work correctly.

So:

User enters 5, 5 is stored in state

User enters 5.5, 5.5 is stored in state

User enters £5.57, 5.57 is stored in state

User enters -5, -5 is stored in state

To do this I've been using the following regex within a .replace() to remove any special characters:

value.replace(/[^0-9.]/, '')

However this removes the minus - character from negative values. I have tried adding it to the capture group like this: replace(/[^0-9.-]/, '') but this matches both -5 and 5 - 3. I would like to retain negative numbers but exclude any other use of the minus symbol.

Any ideas?

Thanks



Solution 1:[1]

This seems to do what you want:

const trimSpecial = x => x
  // first preserve all `-`
  .replace(/[^0-9.-]/g, '')
  // then remove all `-` except, optionally, the one in first position
  .replace(/(?!^-)-/g, '')

const test = x=>console.log(x, "=>", trimSpecial(x))

test("-5.8")
test("$-3")
test("-5-5")
test("6 - 6")

Solution 2:[2]

You can use

value.replace(/(-\d*\.?\d+).*|[^0-9.]/g, '')

Details

  • (?!^)- - a hyphen not at the start of string
  • | - or
  • [^0-9.-] - any char other than a digit, dot or hyphen.

const c = ['5', '5.5', '£5.57', '-5', '-5-5', '5-3'];
const re = /(?!^)-|[^0-9.-]/g;
for (var i of c) {
    console.log(i, '=>', i.replace(re, ''));
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2