...

View Full Version : replace not working for some reason



DanInMa
07-26-2011, 07:20 PM
I am trying to fix some datetime strings so I can convert form values into date objects so I can compare the dates in my validation process. the date time strings look like - 7/21/2011 8:00am

for some reason the am is not being replaced by " am" . here's the function


function ampm(str){

str.replace(/am/gi," am")
str.replace(/pm/gi," pm")
return str
}

for example the result of ampm("8:00am") is 8:00am and not 8:00 am

.. it seems so simple.

DanInMa
07-26-2011, 07:30 PM
nevermind.

Logic Ali
07-26-2011, 07:34 PM
nevermind.It's customary to publish your solution, in this case that in JS strings cannot be altered and must be recreated:

<script type="text/javascript">

function ampm(str)
{
return str.replace( /(am|pm)/i, " $1" );
}

alert( ampm("8:00am") );

</script>

Philip M
07-26-2011, 07:47 PM
str = str.replace(/am/gi," am");
str = str.replace(/pm/gi," pm");

#All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

Krupski
07-26-2011, 09:32 PM
str = str.replace(/am/gi," am");
str = str.replace(/pm/gi," pm");#All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

While we're at presenting helpful hints, here's one of mine:

Usually, coders will write something like this:


text = text.replace(blah1);
text = text.replace(blah2);
text = text.replace(blah3);
....etc....
It can be done this way also:


text = text
.replace(blah1)
.replace(blah2)
.replace(blah3);
It's easier to read than stringing them all together:

text = text.replace(blah1).replace(blah2) .replace(blah3)

Best of all, this hint is absolutely free! :D

(and yes I know "blah" is not valid code...)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum