0

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?

2
  • Can you post an example string? Is it always a known format, or does it vary? Commented Feb 7, 2013 at 3:20
  • Can you show the actual text we're matching against? Not sure if it is 20130206 or 02-06-2013 or 02//06/2013 or... Commented Feb 7, 2013 at 3:21

1 Answer 1

1

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!"
Sign up to request clarification or add additional context in comments.

7 Comments

This did it. str.replace(/\b0\B/, ''); Thank you!
Would you mind explaining what \b does? I realize that \B would be the negation of it, but I don't know what \b stands for.
"b" is for "boundary" - the edge of the character class. If you think this is the correct answer, you should accept it so others will know when they are looking for the answer. They might miss the comments.
@Jonathan, as Devin points out, \b is for (word) boundary. It is a zero width assertion (like a lookahead), and if JavaScript had lookbehinds could be written as (?:(?<=\w)(?!\w)|(?<!\w)(?=\w)).
How does var num = 0 + str; has anything to do with the solution?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.