Replace Function & Regular Expressions

Subscribe to Replace Function & Regular Expressions 5 posts, 3 voices

 
RunningBlind Scriptwright

I'm pretty terrible at regular expressions, and I was wondering if someone could help.

I want to replace something like "December 21, 2006 2:39 PM" with "Dec 21, 2006" to match any date and month in that format, of course.

sString.replace(/\s+\d+:\d+\s+[A-Z]+/, '')

That is what I currently have to replace everything after the year...whitespace, digit(s), colon, digit(s), whitespace, capital alphabet characters (like AM or PM).

That part is good.

Now I just want to get some replace function to replace full month names with their three-letter abbreviations.

 
Mikado Scriptwright

If you don't like RegExp, why use them?

var x = new Date("December 21, 2006 2:39 PM"); alert(x.toDateString());

 
znerp Scriptwright

Something along the lines of the following should do the trick... sString.replace(/(\w{3})\w+(\s\d+,\s\d{4})\s\d:\d+\s[A|P]M/, "$1$2")

 
RunningBlind Scriptwright

Thanks, guys. I used znerp's expression and it worked in most cases, but I messed with a bit and realized he had made a small mistake.

The part for the time -- \d:\d+ -- should be replaced with \d+:\d+, so times with the hour greater than one digit match as well.

Other than that, it's perfect. Thanks.

 
znerp Scriptwright

Oh yeah, my bad. Got a bit overzealous with removing some of your plusses.