Skip to content
This repository was archived by the owner on May 1, 2025. It is now read-only.

Commit be64e07

Browse files
author
Hans Kristian Flaatten
committed
feat(parser): more correct number parsing
This prevents strings with mixed numbers and strings to be parsed as numbers if the string begins with a number. `123abc` will now evaluate to the string instead of `123` with the previous parser.
1 parent 11025e1 commit be64e07

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

index.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,8 @@ module.exports.prototype.parseStringVal = function(string) {
189189
return true;
190190
} else if (this.string.toBoolean && string.toLowerCase() === 'false') {
191191
return false;
192-
} else if (this.string.toNumber && !isNaN(parseFloat(string, 10))) {
192+
} else if (this.string.toNumber && !isNaN(parseInt(string, 10)) &&
193+
(+string - +string + 1) >= 0) {
193194
return parseFloat(string, 10);
194195
} else {
195196
return string;

test.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,14 @@ describe('parseStringVal()', function() {
132132
assert.equal(qs.parseStringVal('000100'), 100);
133133
});
134134

135+
it('returns number for positive parseable integer', function() {
136+
assert.equal(qs.parseStringVal('+100'), 100);
137+
});
138+
139+
it('returns number for negative parseable integer', function() {
140+
assert.equal(qs.parseStringVal('-100'), -100);
141+
});
142+
135143
it('returns number for parseable float', function() {
136144
assert.equal(qs.parseStringVal('10.123'), 10.123);
137145
});
@@ -140,9 +148,33 @@ describe('parseStringVal()', function() {
140148
assert.equal(qs.parseStringVal('00010.123'), 10.123);
141149
});
142150

151+
it('returns number for positive parseable float', function() {
152+
assert.equal(qs.parseStringVal('+10.123'), 10.123);
153+
});
154+
155+
it('returns number for negative parseable float', function() {
156+
assert.equal(qs.parseStringVal('-10.123'), -10.123);
157+
});
158+
143159
it('returns string for empty string', function() {
144160
assert.equal(qs.parseStringVal(''), '');
145161
});
162+
163+
it('returns string for space string', function() {
164+
assert.equal(qs.parseStringVal(' '), ' ');
165+
});
166+
167+
it('returns string for "number string number"', function() {
168+
assert.equal(qs.parseStringVal('123abc123'), '123abc123');
169+
});
170+
171+
it('returns string for "string number"', function() {
172+
assert.equal(qs.parseStringVal('abc123'), 'abc123');
173+
});
174+
175+
it('returns string for "number string"', function() {
176+
assert.equal(qs.parseStringVal('123abc'), '123abc');
177+
});
146178
});
147179

148180
describe('parseString()', function() {

0 commit comments

Comments
 (0)