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.
I have a string that contains 2 numbers (days of the month with leading 0s). I'm trying to remove the leading 0s from the string but not remove the 0 in "10" or "20".
example strings that could be here: "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.
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".
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
:
str.replace(/\b0+\B/g, '');
Example:
"i have 000100 and 0020!".replace(/\b0+\B/g, '')
Returns:
"i have 100 and 20!"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.