Determining variations of Javascript array - javascript

I have an alert dependent on an array containing around 38 of the 50 United States, It works fine (thanks to help from you wonderful people) but now I'm concerned users may input variations of the format I am using currently which is two uppercase letters (i.e. WA, OR, GA etc). What if they are to input lowercase (i.e. wa, or, ga) or maybe a combination of uppercase and lowercase (i.e. Wa, Or, Ga) or with symbols (i.e. WA - Washington, OR - Oregon, GA - Georgia). Wondering if there is a more accurate way of doing this that will catch all variations.
The alert I'm referring to is the last one, at the bottom pointing toward #address_province.
Please note I am very new at using both Javascript and jQuery so as much detail as you can offer is appreciated.
Thank you very much in advance.
<script>
// Hides shipping info fieldset if ship to billing is checked
$(function () {
$("#ship_to_billing").change(function () {
if ($(this).is(":checked")) $("#shipping_info").hide();
else $("#shipping_info").show();
});
});
// Validates address fields are filled out unless ship to billing is checked...
function validateShipping() {
if (!$("#ship_to_billing").is(":checked")) {
var inputs = $("#shipping_info input");
var ready = true;
inputs.each(function () {
if ($(this).val() == '') {
ready = false;
return false;
}
});
if (!ready) {
alert("Please tell us where to send this. Either choose ship to Billing Address or fill out both the Recipient Name as well as Shipping Address fields. Thanks!");
return false;
}
}
// Makes sure age verification is checked
if (!$('#age_verification').is(':checked')) {
alert("Please verify you are 21 years of age or older.");
return false;
}
// Confirms province is allowed for wine shipping
var states = ["AK", "AZ", "CA", "CO", "CT", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "LA", "ME", "MD", "MI", "MN", "MO", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OR", "SC", "TN", "TX", "VT", "VA", "WA", "WV", "WI", "WY"];
if ($.inArray($("#address_province").val(), states) <0) {
alert("Shipping gifts containing alcohol to this state is prohibited by law. Please choose another item.");
return false;
}
return true;
}
</script>

The case concerns can be handled using the String.toUpperCase function. You'd simply take the value they've entered, convert it to upper case, and then compare it against the values in your array. So, regardless of whether they enter WA, Wa, wa, or wA, you'll be using WA for the comparison.
The user entering the value in some other format, such as WA - Washington can be handled in a few ways. One solution would be to simply take the first two characters (so you'd get WA), but that doesn't work if they enter the state name on its own; it would work for Washington, but not for Georgia.
I'd be inclined to enforce a limit of 2 characters on the input box using the maxlength attribute (maxlength="2"). That should be supported by all browsers and makes it clear that you're expecting a state code rather than a state name.
One final option is, if that validation is always applicable, to use a <select> element that only includes valid states. That would remove the need for client-side validation altogether (though you'd still need to do server-side validation).

http://jsbin.com/uQEJIkU/1/edit
$(document).ready(function() {
var state = "Wisconsin";
var result = state.slice(0,2).toUpperCase()
alert(result)
});
All merit goes to #Anthony_Grist as he had the first answer in the comment.

Related

Extract information from string - JavaScript

I am currently implementing google places autocomplete and the module I am using in React Native gives me the address as a whole string and not in address components. However, I need to have the postal code and city separate. The example response always look like this:
address: 'Calle Gran Vía, 8, 28013 Madrid, Spain
From this string I would need to have an object that looks like this:
{
city: 'Madrid',
postal_code: 28013,
}
How could I achieve this?
It's not the most "clean" or "smooth" answer, but it's something:
var response = "address: 'Calle Gran Vía, 8, 28013 Madrid, Spain";
var subStr = response.split(",")[2];
var obj = {
city: subStr.split(" ")[2],
postal_code: subStr.split(" ")[1]
};
console.log(obj);
For the city I think the best way is to use an array of cities and search it in the string
var str = "Calle Gran Vía, 8, 28013 Madrid, Spain";
var cities = ["Paris", "Berlin", "Madrid"];
var city = cities.filter(function(item) {
if (str.search(item) != -1)
return item;
})[0] || null;
For the postal code you should use a regex depending on the country (a good list of regex by country)
Probably split the string by ',' with array methods, take the third element of the array and split that by ' ', then you have your data points.
If you can always count on it being in that same format, you can do the following.
var splitAdress = address.split(",");
//This will give you ["Calle Gran Vía", " 8", " 28013 Madrid", " Spain"]
splitAdress = splitAdress[2].split(" ");
//This will give you ["", "28013", "Madrid"]
You'll first split the string into an array based on the comma and then follow it up by splitting on the space. The extra element in the second array is due to the space. This is an example of what #CBroe pointed out in the comments.
list=adress.split(",")[2].split()
list[0] gives you the postal code
list[1] gives you the city name
It depend on if there is always a comma in the "Calle Gran Vía, 8", if not you can use instead list=adress.split(",")[-2].split()
You might want to try this.
var address="Calle Gran Vía, 8, 28013 Madrid, Spain";
var splits = address.split(',')[2].trim().split(' ');
var newAdd = {
city : splits[1],
postal_code : splits[0]
}
console.log(newAdd);

Extracting data from a string jquery

I have e scenario like this:
I need to build a jQuery function that takes a string as an input and update the string into another string.
The input can be one of these:
A="0"
A="0, 5" (basically can be "0, any_other_digits_different_from_0")
A="0, 58"
A="58" (basically any number that doesn't start with zero)
I want the function to updated to:
if input is option number one (A="0") update A="--"
if input is option number two (A="58") DO NOTHING, leave it A="58"
if input is option number three (A="0, 5" update to A="5"
if input is option number four (A="0, 58") update to A="58"
Option four can have more than two digits after "0, ".
It seems like this can be done by regex somehow but I am not being able to put anything together that can make it work. Any help is appreciated.
You could split the string and take the last value. If zero return '--'.
function getValue(a) {
return (+a.split(', ').pop() || '--').toString();
}
console.log(getValue("0")); // "--"
console.log(getValue("0, 5")); // "5"
console.log(getValue("0, 58")); // "58"
console.log(getValue("58")); // "58"
A proposal with a regular expression searching for last numbers
function getValue(a) {
return (+a.match(/\d+$/) || '--').toString();
}
console.log(getValue("0")); // "--"
console.log(getValue("0, 5")); // "5"
console.log(getValue("0, 58")); // "58"
console.log(getValue("58")); // "58"

Delivery charge for if postcode starts with ?? Javascript or PHP

I have a list of postcodes in the UK with a region id next to it. Now for delivering products it costs more depending on the region a user lives in.
For example, if a user lives in Birmingham and has a postcode that starts with B, he will get free delivery because that postcode region doesn't have any charge.
Likewise, if a user has a postcode starting with IM , they have to pay more delivery as that postcode region is more.
Sample postcode list:
Postcode | Region
AL | A
BA | A
BB | A
BD | A
B | B
BH | B
LN | D
LS | D
IV1 | E
IV23 | F
From the example above if a user wants to get a delivery and their postcode starts with BA then I want to apply the delivery charge rate of region A.
I'm actually a bit confused as to how I can programmatically do this. At first I thought I would simply do something similar to:
$postcodes = [
'AL'=>'A',
'BA'=>'A',
//And so on ....
];
//get the first 2 letters
$user_input = substr( $user_postcode, 0, 2 );
if(array_key_exists($user_input,$postcodes)){
//Get the region code
$region = $postcodes[$user_input];
// Charge the user with the delivery rate specific to that user, then carry on
}
But problem is that some similar postcodes can be in different regions, so for example, IV1 is region E and IV23 is region F like seen above.
That means I have to match a users post code on either, the 1 , 2 ,3 or 4 characters. That probably doesn't make sense. To elaborate more see below:
//From Birmingham and is in region B
$user1_input = 'B';
//From Bradford and is in region A
$user1_input = 'BD';
//From Inverness and is in region E
$user1_input = 'IV1';
So if the user input is from Birmingham and user input starts with B , how can i tell that apart from a postcode that also starts with B but then has other letters in it which makes it a different postcode.
I'm trying my best to explain, hopefully, this does make sense. If not please ask for more info.
Can anyone please help me with the logic to how I could achieve this? Either in Javascript or PHP , because i can convert the logic afterwards.
If you have what looks like a valid UK postcode, then remove the spaces and just search the array till you find a match:
$lookup = [
'' => 'X', // in case no match is found
'AL'=>'A',
'BA'=>'A',
//And so on ....
];
function get_delivery_for($postcode)
{
global $lookup;
for ($x=5; $x>0 && !$result; $x--) {
$result=$lookup[substr($postcode, 0, $x)];
}
return ($result);
}
Note that the code above is intended for illustration, I would recommend using something more elaborate to avoid it throwing warnings....
$result=isset($lookup[substr($postcode, 0, $x)])
? $lookup[substr($postcode, 0, $x)]
: false;
One option would be to order your postcode/region array by the descending length of the postcode key. This way, the longer (more specific) keys are checked first. Taking your list above, it would become something like this...
$postcodes = array(
"IV23" => "F",
"IV1" => "E",
"LS" => "D",
"LN" => "D",
"BH" => "B",
"BD" => "A",
"BB" => "A",
"BA" => "A",
"AL" => "A",
"B" => "B",
);
After you have that, it's as simple as looping through the array, checking for a match against the provided postcode (starting from the left), and stopping when you find a match.
foreach($postcodes as $code => $region)
{
if($code == substr($user_postcode, 0, strlen($code)))
{
$shippingRegion = $region;
break;
}
}
echo $shippingRegion;

Parsing out Salutation & First Name from Full Name field

I have a string that contains Full Name.
The format of the full name may or may not have the salutation. Also there may or may not be a period after the salutation as well (could display as Mr. or Mr). For example, I could receive:
"Mrs. Ella Anderson"
"Ella Anderson"
"Miss Jennifer Sply"
"Mr. Dan Johnson"
"Damien Hearst"
My goal is to remove the salutation from the Full Name string. Once the salutation is removed, I want to parse out the First Name from the Full Name. I am kinda new to regex, but I do understand how to parse out the First Name. The one part I am just not sure how to do is get rid of the salutation.
var string = "Ella Anderson"
var first = string.replace(/\s.*$/, "").toUpperCase().trim();
This regex should work.
var regex = /(Mr|MR|Ms|Miss|Mrs|Dr|Sir)(\.?)\s/,
fullNames = ["Mrs. Ella Anderson", "Ella Anderson", "Miss Jennifer Sply", "Mr. Dan Johnson", "Damien Hearst"];
var names = fullNames.map(function(name) {
var match = regex.exec(name),
n = "";
(match !== null) ? n = name.replace(match[0], "") : n = name;
return n;
});
console.log(names);
The problem is that the full name is in a string in the first place. If at all possible, you should change that to just use separate fields.
There's no telling what users will enter in a text box. Nor is it reliably possible to determine what part of the remaining name is the first name, and what part is the surname.
If the input data is separated properly, you won't have to figure out what is what, any more.
So, if possible, change the way the name is entered to something like:
<select name="select">
<option>Miss</option>
<option>Mrs</option>
<option>Mr</option>
<option>etc...</option>
</select>
<input placeholder="First name" />
<input placeholder="Surname" />
You can use this regexp: /((Mrs|Mr|Miss)\.? )?([^ ]*) ?([^ ]*)/
Examples:
var regex = /((Mrs|Mr|Miss)\.? )?([^ ]*) ?([^ ]*)/;
regex.exec('Mrs. Ella Anderson') == ["Mrs. Ella Anderson", "Mrs. ", "Mrs", "Ella", "Anderson"];
regex.exec("Ella Anderson") == ["Ella Anderson", undefined, undefined, "Ella", "Anderson"];
regex.exec("Miss Jennifer Sply") == ["Miss Jennifer Sply", "Miss ", "Miss", "Jennifer", "Sply"];
regex.exec("Mr. Dan Johnson") == ["Mr. Dan Johnson", "Mr. ", "Mr", "Dan", "Johnson"];
regex.exec("Damien Hearst") == ["Damien Hearst", undefined, undefined, "Damien", "Hearst"];
regex.exec("Missy Jennifer") == ["Missy Jennifer", undefined, undefined, "Missy", "Jennifer"];
If you want the first name and the last name, you just have to look at the last two values of the array.
Of course, this regexp will not work with something like `Mr. John Smith Junior. If you want something generic, don't use a regexp.
It's a pretty complicated regex:
/^(?:(Miss|M[rs]{1,2})\.?\s+)?(\S+)\s+(\S+)$/
Then if you want middle names or initials it gets a little trickier things like jr. or sr. - It's mostly all doable. There's some question about how to deal with hyphenates.
You can use this regexp:^[ \t]*(?<title>(Shri|Leu|DR|mrs|SMT|Major|Gen){1,10}(\.|,))?\s*(?<LstName>[A-Z][a-z-']{2,20}),? +(?<FstName>[A-Z,a-z]+)*[ \t]*[^\n]*
Tested on the following Test data:
Major. Amator Gary L
Mrs. Grundy Ronald
Dr. Domsky Alan
Shri. Worden Scott Allen
Rodriguez Howard W
NEHME ALLEN
RODRIGUEZ CHARLES G
VERGARA WILLIAM F J
EVELYN J
Leu. GLICK, JACOB L.
SMT. Taylor-garcia Dottielou

title casing and Abbreviations in javascript

I am trying to Titlecase some text which contains corporate names and their stock symbols.
Example (these strings are concatenated as corporate name, which gets title cased and the symbol in parens): AT&T (T)
John Deere Inc. (DE)
These corporate names come from our database which draws them from a stock pricing service. I have it working EXCEPT for when the name is an abbreviation like AT&T
That is return, and you guessed it right, like At&t. How can I preserve casing in abbreviations. I thought to use indexof to get the position of any &'s and uppercase the two characters on either side of it but that seems hackish.
Along the lines of(pseudo code)
var indexPos = myString.indexOf("&");
var fixedString = myString.charAt(indexPos - 1).toUpperCase().charAt(indexPos + 1).toUpperCase()
Oops, forgot to include my titlecase function
function toTitleCase(str) {
return str.replace(/([^\W_]+[^\s-]*) */g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
Any better suggestions?
A better title case function may be
function toTitleCase(str) {
return str.replace(
/(\b.)|(.)/g,
function ($0, $1, $2) {
return ($1 && $1.toUpperCase()) || $2.toLowerCase();
}
);
}
toTitleCase("foo bAR&bAz a.e.i."); // "Foo Bar&Baz A.E.I."
This will still transform AT&T to At&T, but there's no information in the way it's written to know what to do, so finally
// specific fixes
if (str === "At&T" ) str = "AT&T";
else if (str === "Iphone") str = "iPhone";
// etc
// or
var dict = {
"At&T": "AT&T",
"Iphone": "iPhone"
};
str = dict[str] || str;
Though of course if you can do it right when you enter the data in the first place it will save you a lot of trouble
This is a general solution for title case, without taking your extra requirements of "abbreviations" into account:
var fixedString = String(myString).toLowerCase().replace(/\b\w/g, String.toUpperCase);
Although I agree with other posters that it's better to start with the data in the correct format in the first place. Not all proper names conform to title case, with just a couple examples being "Werner von Braun" and "Ronald McDonald." There's really no algorithm you can program into a computer to handle the often arbitrary capitalization of proper names, just like you can't really program a computer to spell check proper names.
However, you can certainly program in some exception cases, although I'm still not sure that simply assuming that any word with an ampersand in it should be in all caps always appropriate either. But that can be accomplished like so:
var titleCase = String(myString).toLowerCase().replace(/\b\w/g, String.toUpperCase);
var fixedString = titleCase.replace(/\b\w*\&\w*\b/g, String.toUpperCase);
Note that your second example of "John Deere Inc. (DE)" still isn't handled properly, though. I suppose you could add some other logic to say, put anything word between parentheses in all caps, like so:
var titleCase = String(myString).toLowerCase().replace(/\b\w/g, String.toUpperCase);
var titleCaseCapAmps = titleCase.replace(/\b\w*\&\w*\b/g, String.toUpperCase);
var fixedString = titleCaseCapAmps.replace(/\(.*\)/g, String.toUpperCase);
Which will at least handle your two examples correctly.
How about this: Since the number of registered companies with the stock exchange is finite, and there's a well-defined mapping between stock symbols and company names, your best best is probably to program that mapping into your code, to look up the company name by the ticker abbreviation, something like this:
var TickerToName =
{
A: "Agilent Technologies",
AA: "Alcoa Inc.",
// etc., etc.
}
Then it's just a simple lookup to get the company name from the ticker symbol:
var symbol = "T";
var CompanyName = TickerToName[symbol] || "Unknown ticker symbol: " + symbol;
Of course, I would be very surprised if there was not already some kind of Web Service you could call to get back a company name from a stock ticker symbol, something like in this thread:
Stock ticker symbol lookup API
Or maybe there's some functionality like this in the stock pricing service you're using to get the data in the first place.
The last time I faced this situation, I decided that it was less trouble to simply include the few exceptions here and there as need.
var titleCaseFix = {
"At&t": "AT&T"
}
var fixit(str) {
foreach (var oldCase in titleCaseFix) {
var newCase = titleCaseFix[oldCase];
// Look here for various string replace options:
// http://stackoverflow.com/questions/542232/in-javascript-how-can-i-perform-a-global-replace-on-string-with-a-variable-insi
}
return str;
}

Categories

Resources