Skip to content

Commit 18d0fd5

Browse files
authored
feat: don't coerce number from string with leading '0' or '+' (#158)
BREAKING CHANGE: options with leading '+' or '0' now parse as strings
1 parent ea6ce05 commit 18d0fd5

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

index.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -786,9 +786,14 @@ function parse (args, opts) {
786786
}
787787

788788
function isNumber (x) {
789+
if (x === null || x === undefined) return false
790+
// if loaded from config, may already be a number.
789791
if (typeof x === 'number') return true
792+
// hexadecimal.
790793
if (/^0x[0-9a-f]+$/i.test(x)) return true
791-
return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x)
794+
// don't treat 0123 as a number; as it drops the leading '0'.
795+
if (x.length > 1 && x[0] === '0') return false
796+
return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x)
792797
}
793798

794799
function isUndefined (num) {

test/yargs-parser.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2770,6 +2770,24 @@ describe('yargs-parser', function () {
27702770
argv.foo.should.equal(9.39404959509494e+22)
27712771
})
27722772

2773+
// see: https://github.com/yargs/yargs/issues/1099
2774+
it('does not magically convert options with leading + to number', () => {
2775+
const argv = parser(['--foo', '+5550100', '--bar', '+5550100'], {
2776+
number: 'bar'
2777+
})
2778+
argv.foo.should.equal('+5550100')
2779+
argv.bar.should.equal(5550100)
2780+
})
2781+
2782+
// see: https://github.com/yargs/yargs/issues/1099
2783+
it('does not magically convert options with leading 0 to number', () => {
2784+
const argv = parser(['--foo', '000000', '--bar', '000000'], {
2785+
number: 'bar'
2786+
})
2787+
argv.foo.should.equal('000000')
2788+
argv.bar.should.equal(0)
2789+
})
2790+
27732791
// see: https://github.com/yargs/yargs-parser/issues/101
27742792
describe('dot-notation array arguments combined with string arguments', function () {
27752793
it('parses correctly when dot-notation argument is first', function () {

0 commit comments

Comments
 (0)