If you need to verify whether the initial value is not zero, a simple substr can be used:
Inputvalue.substr(0,1) !== '0'
If you wish to replace all leading zeros:
Inputvalue.replace(/^0+/, '');
The ^
denotes 'string begins with', followed by 'one or more' (+
) zeros.
To replace all leading zeros before a digit (\d
):
Inputvalue.replace(/^0+\d/, '');
The ^
indicates 'string starts with', proceeded by 'one or more' (+
) zeros.
If your goal is to extract the first digit following the zeros:
The ^
symbol signifies 'start of string'. For instance, in 000001
, the 1
isn't at the beginning of the string, thus it won't match.
I often find it useful to describe my objectives:
- I want the initial single digit ->
[1-9]
- Commences with (
^
) one or more (+
) zeros -> ^0+
This leads to ^0+[1-9]
.
To solely capture the digit, enclose it in a group: ^0+([1-9])
const examples = [
'123', // no starting zeroes
'0123', // matching
'000123', // matching
'132000123', // no matching zeros, also no match towards the end!
];
console.log(examples.map(function (example) {
const matches = example.match(/^0+([1-9])/);
return example + ' -> ' + (matches !== null ? matches[1] : 'no match!');
}));