[thelist] javascript / regex conundrum

Lee Kowalkowski lee.kowalkowski at googlemail.com
Fri Oct 17 16:02:52 CDT 2008


2008/10/17 Jeremy Weiss <eccentric.one at gmail.com>:
> I have a page that is currently displaying information on when an open house is scheduled. Unfortunately everything (date, time, comments, etc.) is in a single field. And there's no limit on how many events may be in the field. The client is wanting me to change the time values from 24 hour to 12 hour. And due to a long list of factors that I can't change, I have to do this in JavaScript.
>
> Here's a sample of what could be in that field:
>
> 1 - Date:10/18/2008, Time:1300-1600, Type:PUB, Comment: 2 - Date:10/19/2008, Time:1300-1600, Type:PUB, Comment:';

Hi Jeremy,

Did you know you can pass a function to String.replace()?  Like this:

--
function confuseVisitorReplace(match, hour)
{
  var newHour = hour;
  if(newHour > 12)
  {
    newHour -= 12;
  }

  return match.replace(hour, newHour + ':');
}

var field = '1 - Date:10/18/2008, Time:1300-1600, Type:PUB, Comment: 2
- Date:10/19/2008, Time:1300-1600, Type:PUB, Comment:';
var confuseVisitorFormat = field.replace(/[:\-](\d{2})\d{2}/g,
confuseVisitorReplace);
--

Apologies for the facetious variable names, but how exactly are the
visitors to know not to turn up 12 hours early?

-- 
Lee



More information about the thelist mailing list