1

My goal is :

Delete all. except the numbers , but delete the zeros who before numbers 1 to 9

And I have this regex:

var validValue = inputValue.replace(/[^\d]/g, '').replace(/^0*/g, '');

But I want to make it in a one replace()

So how can I do that ?

Moti Winkler
  • 308
  • 1
  • 4
  • 19

1 Answers1

1

You want to remove all leading zeros and all non-digit symbols. It can be done with

/^0+|\D+/g

See the regex demo

The regex matches

  • ^0+ - 1 or more leading digits (those at the beginning of the string)
  • | - or
  • \D+ - one or more non-digit symbols

var re = /^0*|\D+/g; 
var str = '00567600ffg5566';
var result = str.replace(re, '');
document.body.innerHTML = str + " >>> " +  result;
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Thank you ! Thank you also for the explanation! – Moti Winkler Mar 10 '16 at 14:58
  • 2
    @Thomas: [It works](https://regex101.com/r/fS1yC8/4). It removes the leading zeros and all non-digits inside the string. Moti, the `/g` in `/^0*/g` makes no sense since the start of string can only be matched once. Also, this regex may match an empty string, thus, it is best to replace the `*` with the `+` quantifier. – Wiktor Stribiżew Mar 10 '16 at 14:59