help with a couple lines of code please? string matching.

D

DanH

I am not a javascript person but I need a line or two of code.
Hopefully one of you guys can help please.

Here's my problem. I have a string called 'mystate' and I need to
assign a variable either a 1 or a 2 depending on what it is.
'ND','SD',and 'PA' should return a 2, whereas 'CA', 'TX', and 'NY'
should return a 1.

I am trying to use a 'match' expression and a '?:' but everything so far
has not worked. Still working at it though :).

Anyway, if anyone can help i would appreciate it. Thx.
 
M

McKirahan

DanH said:
maybe match isn't the way to go. What I am trying to do is something
like this, with a comma delimited list of states. But this isn't correct.

compare(${mystate},("ND","SD","PA")) ? 2 : 1

Perhaps you want something like this?

function myState(mystate) {
var valu = 0;
if (mystate.length == 2) {
if ("ND,PA,SD".indexOf(mystate) >= 0) valu = 1;
if ("CA,NY,TX".indexOf(mystate) >= 0) valu = 2;
}
return valu;
}
 
D

DanH

McKirahan said:
Perhaps you want something like this?

function myState(mystate) {
var valu = 0;
if (mystate.length == 2) {
if ("ND,PA,SD".indexOf(mystate) >= 0) valu = 1;
if ("CA,NY,TX".indexOf(mystate) >= 0) valu = 2;
}
return valu;
}

Perhaps. :) I had to look up indexOf but I see what you are doing.
Thank you very much.

Dan
 
M

McKirahan

DanH said:
Perhaps. :) I had to look up indexOf but I see what you are doing.
Thank you very much.

Dan

[snip]

Oops, I had the states reversed; it should be:

function myState(mystate) {
var valu = 0;
if (mystate.length == 2) {
if ("CA,NY,TX".indexOf(mystate) >= 0) valu = 1;
if ("ND,PA,SD".indexOf(mystate) >= 0) valu = 2;
}
return valu;
}
 
D

Dr John Stockton

JRS: In article <[email protected]>,
dated Wed, 3 Nov 2004 02:19:58, seen in DanH
Here's my problem. I have a string called 'mystate' and I need to
assign a variable either a 1 or a 2 depending on what it is.
'ND','SD',and 'PA' should return a 2, whereas 'CA', 'TX', and 'NY'
should return a 1.


One line : x = 1 + ("CA TX NY ND SD PA ".indexOf(mystate)/9)|0
One line : x = {SD:2, ND:2, PA:2, CA:1, TX:1, NY:1}[mystate]
Probably better :
Ob = {SD:2, ND:2, PA:2, CA:1, TX:1, NY:1}
x = Ob[mystate]
Tested; legal, AFAIK.

Not recommended, but using match (OK in IE4) :
"CA TX NY ND SD PA ".match(mystate)
x = 1 + (RegExp.lastIndex/9)|0
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top