[英]Regex match for specific number before but not after in javascript
I just suck at regex. 我只是在正则表达式。 I've been reading at http://www.regular-expressions.info/tutorial.html but I can't figure out how to write this. 我已经在http://www.regular-expressions.info/tutorial.html上阅读了,但是我不知道该怎么写。
I have a string that contains 2 numbers (days of the month with leading 0s). 我有一个包含2个数字的字符串(一个月的前几天为0)。 I'm trying to remove the leading 0s from the string but not remove the 0 in "10" or "20". 我正在尝试从字符串中删除前导0,但不删除“ 10”或“ 20”中的0。
example strings that could be here: "01","02","03","10","11","12","20","31" 可能在此处的示例字符串:“ 01”,“ 02”,“ 03”,“ 10”,“ 11”,“ 12”,“ 20”,“ 31”
since the string is always a day of the month, it will always be 2 characters in length and always between 01 and 31. 由于字符串始终是一个月中的某一天,因此长度始终为2个字符,且始终在01到31之间。
currently I'm using this (which is obviously wrong): 当前我正在使用它(这显然是错误的):
string.replace(/0/,'');
What I'm trying to end up with is this: "1" instead of "01", "2" instead of "02", "10" without losing the "0". 我要结束的是:“ 1”而不是“ 01”,“ 2”而不是“ 02”,“ 10”而不会丢失“ 0”。
Hopefully this is clear enough. 希望这已经足够清楚了。
How do I do this correctly? 如何正确执行此操作?
If the string only contains the number you could just convert it to an integer, eg: 如果字符串仅包含数字,则可以将其转换为整数,例如:
var num = +str;
If you want to replace parts of a larger string, you can use \\b
: 如果要替换较大字符串的部分,可以使用\\b
:
str.replace(/\b0+\B/g, '');
Example: 例:
"i have 000100 and 0020!".replace(/\b0+\B/g, '')
Returns: 返回值:
"i have 100 and 20!"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.