[英]Remove extra zeros from a string
我知道从字符串中删除前导零的方法:
'000100'.replace(/^0+/, '')
但是,如果像字符串这样的浮点数(例如'00100.2300'或'00100'),如何从中删除所有多余的零?
'00100.2300' => '100.23'
'00100' => '100'
'00100.0023' => '100.0023'
'100.00' => '100.' or '100' will better
'-100.002300' => '-100.0023'
'0.50' => '0.5'
假设字符串:
Number.MAX_SAFE_INTEGER
用于过滤多余零的函数可能相对容易,并且步骤也更多。
和一个正则表达式将更简单。
正则表达式:
^0+(?!\.)|(?:\.|(\..*?))0+$
分解:
^0+(?!\\.)
匹配不符合小数点的前导零 |
要么 (?:
非捕获组的开始
\\.
匹配小数点 |
要么 (\\..*?)
捕获小数点后的数字 )
NCG结束 0*$
匹配尾随零 JS代码:
var str = `00100.2300 00100 00100.0023 100.00 100. 00.50 0.5`; console.log( str.replace(/^0+(?!\\.)|(?:\\.|(\\..*?))0+$/gm, '$1') )
您可以尝试的方法是本机方法:
parseFloat("000100.2300")
然后,您可以使用所需的任何方法将其转换回字符串。
您可以使用^0+
捕获前导零,并使用(\\.\\d*[1-9])(0+)$
捕获尾随零。 因此,您的正则表达式应为:/ /^0+|(\\.\\d*[1-9])(0+)$/g
var res = '00100.2300'.replace(/^0+|(\\.\\d*[1-9])(0+)$/g, '$1'); console.log(res); var res2 = '100'.replace(/^0+|(\\.\\d*[1-9])(0+)$/g, '$1'); console.log(res2);
在我看来,您可以执行一次查找和替换操作即可完成
一切。
这样,您一次就能匹配整个有效数字,从而使您能够
如果在全局范围内完成,则在单个字符串中固定多个数字。
如果您的字符串包含单个数字,则也可以使用相同的功能。
查找(?:(-)(?![0.]+(?![\\d.]))|-)?\\d*?([1-9]\\d*|0)(?:(?:(\\.\\d*[1-9])|\\.)\\d*)?(?![\\d.])
替换$1$2$3
JS演示: https : //regex101.com/r/H44t6z/1
可读/信息版本
# Add behind boundary check here
# -----------------
(?:
( - ) # (1), Preserve sign -
(?! # Only if not a zero value ahead
[0.]+
(?! [\d.] )
)
| # or
- # Match sign, but dump it
)?
\d*? # Dump leading 0's
( # (2 start), Preserve whole number
[1-9] # First non-0 number
\d* # Any number
| # or
0 # Just last 0 before decimal
) # (2 end)
(?: # Optional fraction part
(?: # -------------
( # (3 start), Preserve decimal and fraction
\. # Decimal
\d* # Any number
[1-9] # Last non-0 number
) # (3 end)
| # or
\. # Match decimal, but dump it
) # -------------
\d* # Dump trailing 0's
)?
(?! [\d.] ) # No digits or dot ahead
即使传递了字符串100
此答案也可以解决任务:
'00100.002300'.replace(/^0+|(\.0*\d+[^0]+)0+$/g, '$1')
100.0023
'00100'.replace(/^0+|(\.0*\d+[^0]+)0+$/g, '$1')
100
在这里使用JS类型强制可能是一个主意。
var trim = s => +s+'', strs = ['00100.2300','00100','00100.0023','100.0023'], res = strs.map(trim); console.log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.