/    Sign up×
Community /Pin to ProfileBookmark

Extracting first 2 bytes of a string…..

A request from a javascript light-weight……
I want to query a field (zipcode) and extract the 2 leftmost bytes.
Specific 2-byte pair values will result in links to specific pages.
If the pairs do not match these values, a link to a default page occurs.

I can code this in vbscript……
———-

DIM zipcode as String
DIM pair as String
pair = Left$(zipcode,2)

If pair = “11” then goto NewYork elseif pair = “07” then goto NewJersey elseif pair = “08” then goto NewJersey else goto Default.
———-

I can’t figure out how to get this into a javascript.
The value for zipcode will come from an input box in a form.
Any help you can provide will be much appreciated.
Thanks,

Vince (stuck in the 80’s)

to post a comment
JavaScript

9 Comments(s)

Copy linkTweet thisAlerts:
@A1ien51Nov 08.2009 — To get the first two characters, use substr

Eric
Copy linkTweet thisAlerts:
@vincegauthorNov 09.2009 — Eric,

Thanks for the info. I followed a thread that took me to 'slice'

In this example,

.......

var str1 = "07010";

var str2 = str1.slice(0, -3);

print(str2);

.......

I think str2 yieds "07"

Where can I find help with the "If ... then ...else" part of my problem?

Thanks again,

Vince G.
Copy linkTweet thisAlerts:
@A1ien51Nov 09.2009 — Why would you use -3?

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/if...else

JavaScript does not have goto so guessing you want to make a separate function

Eric
Copy linkTweet thisAlerts:
@jamesbcox1980Nov 09.2009 — Negative numbers count from the end of the array. You want the FIRST 2 numbers, so you need to count from the beginning of the array. (this won't really matter for this particular instance, since your zip-codes [should be?] always 5 digits). But you would actually use "str1.slice(0,2)" instead.

Slice isn't really the best method here. Slice is supposed to be used to slice off pieces of "pie" from strings and arrays. Although it might not be an issue in this script, the faster (CPU wise) method would be String.substr([I]start[/I],[I]length[/I]). So you would use: "var str2=str1.substr(0,2)".

As for setting your page depending on the numbers, there are several methods for this. Here's a simple method that I would use if I were starting out learning about JS:

[CODE]
<script type="text/javascript">
//set the default URL

var def="http://www.yoursite.com/Default";

//create a non-indexed array with the corresponding values
var URLs=[];
URLs["10"]="http://www.yoursite.com/NewYork";
URLs["30"]="http://www.yoursite.com/Atlanta";
URLs["71"]="http://www.yoursite.com/Lafayette";
URLs["77"]="http://www.yoursite.com/Houston";
URLs["94"]="http://www.yoursite.com/SanFransisco";

function goto(zip)
{
//get the first two bytes
ind=zip.substr(0,2);

//check if zip has a corresponding URL
if(typeof URLs[ind]=='string' && URLs[ind]>'') window.location=URLs[ind];
//if not use default
else window.location=def;
}

</script>
<input type="text" id="zip-code" name="zip-code" /><input type="button" value="Go" onclick="goto(document.getElementById('zip-code').value)" />
[/CODE]
Copy linkTweet thisAlerts:
@jamesbcox1980Nov 09.2009 — P.S.

I used strings in the Array indices because using number types will set an array length based on the numbers given. Not only will this will result in several undefined elements, it will also not parse leading zeros and will require more code to parse. Again, this may not be an issue, but I'm trying to use as much foresight as possible.

Also, you do realize you're asking this question in Java[B]Script[/B] and not Java, correct? Judging by your question, it appears you were trying to give an example of what you were trying to do based on something like BASIC, so I'm just wondering.
Copy linkTweet thisAlerts:
@rnd_meNov 09.2009 — P.S.

I used strings in the Array indices because using number types will set an array length based on the numbers given. Not only will this will result in several undefined elements, it will also not parse leading zeros and will require more code to parse. Again, this may not be an issue, but I'm trying to use as much foresight as possible.
[/QUOTE]


then use an object, not an array.

why initialize all that array.prototype overhead of you don't use it?

also, how do you figure substr is any faster than slice?

.substr had to do addition that slice doesn't right?

my benches show .slice actually being a hair faster, though .substr does have the advantage of working in IE4...




[CODE]function goto(zip){
window.location.href=URLs[zip.slice(0,2)]||def;
}
[/CODE]
Copy linkTweet thisAlerts:
@jamesbcox1980Nov 09.2009 — In my tests, every browser except chrome ran substr:slice an average 1:1.0024. Chrome ran slice:substr at 1:1.039. It's not much of a difference and may not matter at all here, as I said. I'm sure the tests will vary with different clock usages.

Neither do any addition. slice() treats strings as arrays, (as strings are) and each character is an element of the array. substr() treats the string as a series of bytes and climbs down the ladder, stores each character/element at the start point until the end point and exits then exits the loop. Slice also climbs the ladder. So, slice() can be slightly bulkier, depending on the application, but not in this case.

Once again, either method will do in this situation. I don't even know why I mentioned it, except that it was what I would use.
Copy linkTweet thisAlerts:
@rnd_meNov 09.2009 — In my tests, every browser except chrome ran substr:slice an average 1:1.0024. Chrome ran slice:substr at 1:1.039. It's not much of a difference and may not matter at all here, as I said. I'm sure the tests will vary with different clock usages.

Neither do any addition. slice() treats strings as arrays, (as strings are) and each character is an element of the array. substr() treats the string as a series of bytes and climbs down the ladder, stores each character/element at the start point until the end point and exits then exits the loop. Slice also climbs the ladder. So, slice() can be slightly bulkier, depending on the application, but not in this case.
[/QUOTE]


thanks for running some benches. It'd been a couple years since i ran any, looks like browsers have changed. I was also testing on 250kb strings, so perhaps that matters... The differences i noted were much less than one percent, so performance is not much on an issue either way...

what's weird is that according to the spec (pg 103+105), slice() takes 8 steps but substr() takes 9...

Also, i got mixed up: it's slice() that uses addition.

but, this is instead of extra min/max calls, which the addition is much faster than, so addition is a good thing here.

i didn't notice anything about treating strings as an array for slice, or slice being operationally different than substr, other than API.

are you referring to a specific browser's implementation?
Copy linkTweet thisAlerts:
@jamesbcox1980Nov 09.2009 — I was also testing on 250kb strings, so perhaps that matters[/QUOTE]

I ran these on both large and small strings and loops and then averaged the numbers (they were so close, it wasn't worth viewing them separately.
×

Success!

Help @vinceg spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...