File tree Expand file tree Collapse file tree 3 files changed +15
-7
lines changed Expand file tree Collapse file tree 3 files changed +15
-7
lines changed Original file line number Diff line number Diff line change @@ -38,7 +38,8 @@ function unicodeToChar(text: string): string {
3838/**
3939 * Convert to string as possible
4040 */
41- const numberRegEx = new RegExp ( '^[+-]?\\d+(\\.\\d+)?$' ) ;
41+ const numberRegEx = new RegExp ( '^[+-]?\\d*\\.?\\d*([Ee][+-]?\\d+)?$' ) ;
42+ const notEmptyRegEx = new RegExp ( '^.+$' ) ;
4243/**
4344 * Try to convert something to number
4445 *
@@ -48,7 +49,7 @@ function tryConvertNumber(input: any) {
4849 if ( typeof input === 'number' ) {
4950 return input ;
5051 }
51- if ( typeof input === 'string' && numberRegEx . test ( input ) ) {
52+ if ( typeof input === 'string' && numberRegEx . test ( input ) && notEmptyRegEx . test ( input ) ) {
5253 try {
5354 return parseFloat ( input ) ;
5455 } catch ( err ) {
Original file line number Diff line number Diff line change @@ -61,8 +61,15 @@ test('tryConvertNumber output test', (t) => {
6161 t . is ( util . tryConvertNumber ( 123 ) , 123 ) ;
6262 t . is ( util . tryConvertNumber ( '123' ) , 123 ) ;
6363 t . is ( util . tryConvertNumber ( 'abc' ) , 'abc' ) ;
64- t . is ( util . tryConvertNumber ( '123abc' ) , 123 ) ;
64+ t . is ( util . tryConvertNumber ( '123abc' ) , '123abc' ) ;
6565 t . is ( util . tryConvertNumber ( 'abc123' ) , 'abc123' ) ;
66+ t . is ( util . tryConvertNumber ( '12e3' ) , 12000 ) ;
67+ t . is ( util . tryConvertNumber ( '123.12' ) , 123.12 ) ;
68+ t . is ( util . tryConvertNumber ( '123.' ) , 123 ) ;
69+ t . is ( util . tryConvertNumber ( '.123' ) , 0.123 ) ;
70+ t . is ( util . tryConvertNumber ( '.123.' ) , '.123.' ) ;
71+ t . is ( util . tryConvertNumber ( '.123.1' ) , '.123.1' ) ;
72+ t . is ( util . tryConvertNumber ( '' ) , '' ) ;
6673 const obj = { } ;
6774 t . is ( util . tryConvertNumber ( obj ) , obj ) ;
6875} ) ;
Original file line number Diff line number Diff line change @@ -86,15 +86,15 @@ function capitalizeFirstLetter(str) {
8686/**
8787 * Convert string to number as possible
8888 */
89- // const numberRegEx = new RegExp('^[+-]?(\\d+)?(\\.\\d+)?$');
89+ const numberRegEx = new RegExp ( '^[+-]?\\d*\\.?\\d*([Ee][+-]?\\d+)?$' ) ;
90+ const notEmptyRegEx = new RegExp ( '^.+$' ) ;
9091function tryConvertNumber ( str ) {
9192 if ( typeof str === 'number' ) {
9293 return str ;
9394 }
94- if ( typeof str === 'string' ) {
95+ if ( typeof str === 'string' && numberRegEx . test ( str ) && notEmptyRegEx . test ( str ) ) {
9596 try {
96- const parsedNumber = parseFloat ( str ) ;
97- if ( ! Number . isNaN ( parsedNumber ) ) return parsedNumber ;
97+ return parseFloat ( str ) ;
9898 } catch ( err ) {
9999 // pass
100100 }
You can’t perform that action at this time.
0 commit comments