Home > Net >  Regex - Remove special characters but retain negative numbers
Regex - Remove special characters but retain negative numbers

Time:05-08

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

CodePudding user response:

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")

CodePudding user response:

You can use

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

Details

  • (-\d*\.?\d ) - Capturing group 1 ($1): a hyphen, zero or more digits, and optional dot and one or more digits
  • .* - any zero or more chars other than line break chars, as many as possible
  • | - or
  • [^0-9.] - any char other than a digit or dot.

The $1 replacement keeps the negative numbers in the resulting string.

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

  • Related