...

View Full Version : Change form entry



florida
06-15-2009, 02:15 AM
I have a form with firstname in one field and lastname is another field.

I need to manipulate the entry so if someone enters Joe for the firstname and Smith for the second name it will be changed to Smith,Joe.

Here is my attempt but it just switched the fields and didnt manipulate how I wanted it:



var name = "Joe Smith"
var pattern = /^([a-z-]+)\s+([a-z-']+)$/gi;
name = name.replace(pattern, "$2,$1");
name = name.replace(/,/, " ");

Old Pedant
06-15-2009, 07:07 AM
Ummm...if first and last names are in SEPARATE fields, then WHERE do you want to put the new combined name??? And why would you ever put them together in the wrong way, as you seem to have done there, instead of just starting out right??

And not to ask a silly question, but why did you do the second replace call, to get rid of the comma that the first call put in there????

Old Pedant
06-15-2009, 07:28 AM
Agreed. But he *said* it was two fields.

But even so, assuming a single field, I don't understand the point of the
name = name.replace(/,/, " "); line. All that does is get rid of the comma that was just put in there.

Oh...and what happens if the name is "Mon'skij O'Brien"? <grin/>

Seems to me a more sensible pattern might be simply:


var pattern = /^\s*([^\s]+)\s+([^\s]+\s*$/i; // should *NOT* be /g!

Or, of course, use word/non-word instead of non-space/space.

Finally, what does he do in the case that somebody enters *THREE* (or more) names?
Dwight David Eisenhower
George Herbert Walker Bush


I'm a troublemaker.

How about this code, instead?


var name = " George Herbert Walker Bush ";
name = name.replace(/^\s+/,"").replace(/\s+$/,"").replace(/\s{2,}/," ");
var lastSpace = name.lastIndexOf(" ");
name = name.substring(lastSpace+1) + ", " + name.substring(0,lastSpace);

Utterly untested, as usual. But must be close.

Philip M
06-15-2009, 07:44 AM
Agreed. But he *said* it was two fields.

Phew, you are quick! You replied to my post which was up only a minute before I deleted it as not adding to yours.



How about this code, instead?


var name = " George Herbert Walker Bush ";
name = name.replace(/^\s+/,"").replace(/\s+$/,"").replace(/\s{2,}/," ");
var lastSpace = name.lastIndexOf(" ");
name = name.substring(lastSpace+1) + ", " + name.substring(0,lastSpace);

Utterly untested, as usual. But must be close.

A small change:-

name = name.replace(/^\s+/,"").replace(/\s+$/,"").replace(/\s{2,}/g," ");

Then it works just fine! Also tested with Mon'skij O'Brien and Jean-Paul O'Flanagan-Clancy. :thumbsup:

Old Pedant
06-15-2009, 07:49 AM
oops...my face is red.

Fun stuff. Will be interesting to hear what the real story is.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum