How to get ISO country code in google-libphonenumber Js package - javascript

I am creating new service, and need country ISO code based on mobile number. I am using google-libphonenumber package but in this package it giving information based on mobile and country ISO code.
I searched on google about this and offical npmjs site https://www.npmjs.com/package/google-libphonenumber but didn't get as per my requirement.
const phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
const number = phoneUtil.parseAndKeepRawInput('7358469469', 'IN');
const number = phoneUtil.parse('7358469469');
Expected result: I am expecting country ISO code based on mobile no.
Actual result: parseAndKeepRawInput and parse function expecting mobile and country ISO code to return detail information.

This is mission impossible, a phone number can be valid in various country. Phone number 7358469469 can be in India (+91-7358469469) or China (+86-7358469469) or any other countries.
However, if the phone number starts with +, you can parse the number and extract the country code, according to the country code specification. Please refer to https://countrycode.org/ for all countries' code list.

I was able to solve this problem by using the following code
const getRegionCodeForNumber = (number, defaultCountryCode = 'US') => {
const phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance()
const numberObj = phoneUtil.parseAndKeepRawInput(number, defaultCountryCode)
return phoneUtil.getRegionCodeForNumber(numberObj)
}
Calling it like this:
console.log(getRegionCodeForNumber('7358469469', 'IN'))
gives IN.
However #shaochuancs is right, to get something meaningful you'll need to pass the number in the international format starting with +, e.g.:
console.log(getRegionCodeForNumber('+86-7358469469', 'IN'))
gives CN.
The second parameter of getRegionCodeForNumber is default country code which the function will fall back to when the international country code with + is omitted.

Related

formating UK mobile to international number with Zapier Code Javascript function

The scenario is...
A visitor comes to my landing page and completed the form, which included a telephone number.
Using Zapier I then pass that form data to ActiveCampaign.com using a "ZAP".
However as ActiveCampaign is in USA, they require the phone number formatting to international standard, instead of local UK.
Most numbers in UK are 07788990022
But it needs to be presented as +447788990022
So I need to use this built in function of Zapier listed below
https://zapier.com/help/code/
And need some Javascript code writing that will check the number
Is it valid UK mobile number? I.e. 11 digits
Remove all spaces, and trim
If 2nd character is a 7 then replace 1st character (which should be a 0) with +44
I really dont have any idea how to do this! I was hoping for a built in function on Zapier, but apparently not. Any ideas would be awesome!!!
David here, from the Zapier Platform team.
This seems like a pretty straightforward js question! This will be pretty "dumb" validation, but will work assuming the input is correct.
You'll have a code (javascript) step and set the input to be phone: input from step 1. Your code will look like this:
var ph = inputData.phone.replace(/\s+/g, '') // remove all whitespace from string
if (ph.length !== 11) {
// invalid phone number. do nothing?
return []
}
if (ph[1] === '7') {
ph = '+44' + ph.substr(1)
}
return {formattedNumber: ph}

Extracting valid date from a string

I need to extract a valid date from a list of random strings. The date can be present in any date format("01/25/16", "25/01/2016", "20-01-2016", "3-Nov-2016" etc) with different kind of separators.
I tried the using Date.parse() and new Date() but these method also return a valid value for any number passed which ideally is not a date.
For Ex: Date.parse("1") = 978336000000
My current solution is to check each string with the following regex
if(!string.match(/^\d+$|[a-zA-Z]+\s*[a-zA-Z0-9]*/) && (string.length > 7)) {
const date = Date.parse(string)
return (!isNaN(date))
}
This regex works to identify date strings like "01/25/16", "25/01/2016", "20-01-2016"
This regex matches most of the regular text like "100", "hello", "123hello", "1h ello12" and lets in values like "123-123", "01/25/16" and Date.parse() identifies pretty good.
But this misses the date string like "23-Nov-2016" so I added one more regex along with previous one
if(((!string.match(/^\d+$|[a-zA-Z]+\s*[a-zA-Z0-9]*/) && (string.length > 7)) || ((string.match(/^\d+$|[a-zA-Z]+\s*[a-zA-Z0-9]*/) && string.toLowerCase.match(/jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec/))) {
const date = Date.parse(string)
return (!isNaN(date))
}
I definitely believe that there exists a much simpler solution than using this large sets of regex in javascript.
EDIT : I don't control the date input rules to specifically validate certain formats.
Unfortunately, I don't think there is a better solution than using a set of regular expressions.
The problem is that there are at least a million different ways to write the same date. It seems like no matter what date formats you have planned for, your users will always come up with something that doesn't fit. So I approached this in the following way for a project I'm working on:
Make a list of acceptable date formats.
Tell the users not to use different formats and enforce it via client-side validation.
In my case, I'm living in the US, and dates are usually written like 'M/D/YY'. To allow for a reasonable range of variation, I wrote my code to accept M/D/YY, M/D/YYYY, and M/D (where the current year is substituted if the year is omitted). These formats are recognized using regular expressions then parsed using the Moment.js library.
You may want to expand the list of permitted formats if your users habitually use them - that's fine. But the important thing is to realize that you can't plan for all possible formats - there are just too many variations.
If you can meet your users' expectations 90% of the time (with the most common formats) and train your users that these are the accepted formats, you'll have happy users and date parsing code that's not 10,000 lines long.

How to calculate numbers using international numeral systems in JavaScript/jQuery and HTML?

If you are calculating two numbers that use the notation of another numeral system, how do you convert the numbers so they can be used in calculations?
Using Globalize.js to Allow International Number Formatting
jQuery offers a script developed with Microsoft called globalize.js that formats numbers based on a locale. In this jsFiddle, I used Spain as the locale as an example, but its capable of many more formats and locales. Try using notation like 1.234,56 to check calculations. You can use the toLocaleString() function to format the calculated number back to a localized format, but this currently only works in Chrome and IE. You could use regex for the other browsers, but this is all I had time for. Here is the basic script, but look at the jsFiddle to see the other js required and the changes that needed to be made to the form tags.
<script>
function Sumar() {
var num1 = Globalize.parseFloat(document.getElementById("txtNumber1").value);
var num2 = Globalize.parseFloat(document.getElementById("txtNumber2").value);
resultado = num1 + num2;
document.getElementById("p").innerHTML = "The result is " + resultado.toLocaleString("es-ES");
}
</script>

jQuery Globalization. Pass currency unit as argument for C format

I am setting up a multilingual site that deals with currencies. I want to be able to display correct currency formats based on the selected language. The server side PHP stuff is a doddle. Using a combination of PHPs NumberFormatter and strftime I have been able to format currencies and dates correctly.
There is however a requirement to have the same degree of formatting done client side with javascript.
I have come across Globalization (former jQuery plugin) and it looks quite promising.
If I want to display a dollar value in American English I can do something like this:
jQuery.preferCulture("en-US");
// Formatting price
var price = jQuery.format(3899.888, "c");
//Assigning stock price to the control
jQuery("#price").html(price);
and this will output:
$3,899.89
While doing:
jQuery.preferCulture("fr-FR");
// Formatting price
var price = jQuery.format(3899.888, "c");
//Assigning stock price to the control
jQuery("#price").html(price);
outputs:
3 899,89 €
which looks perfect. however, I have a need to output multiple currencies. So, if I have 'fr-FR' selected as my preferred culture, how can I output, say, a dollar value like so:
3 899,89 $
so that the format is French, but the value is American Dollar. I have looked but not found anyway to pass a currency symbol as an argument.
The only documented way to modify the currency symbol in Globalize is to change the numberFormat.currency.symbol property of a given culture—in this case, the fr-FR culture. This will kind of do what you want, but it’s not a very elegant solution, and you would need to manually build a table of correct symbols for each locale and write another method to swap them out. (n.b. It is possible to pass a third argument to Globalize.format with a different locale identifier, but this just formats the number using that locale’s cultural settings.) Looking at the culture definition syntax, there is simply no provision for displaying different currencies using a given locale.
If you were to look elsewhere, the dojo/currency module in the Dojo Toolkit does do exactly what you need, using data from the Unicode Common Locale Data Repository to determine how to represent various currencies in different locales. So you can set your locale to fr, write currency.format(3899.888, { currency: "USD" }), and it will output the currency in USD in the correct format for the French locale.
I had the same problem, in the end I just replaced the default currency symbol on the output with the symbol I wanted to display. It's a bit primitive but it keeps the formatting correct for the locale with the currency symbol you want.
function formatCurrency(value, format, symbol){
var formattedValue = Globalize.format(value, format);
if (typeof symbol === "string") {
formattedValue = formattedValue.replace(Globalize.culture().numberFormat.currency.symbol, symbol);
}
return formattedValue;
}
document.getElementById("price1").innerHTML = formatCurrency(123.34,"c"); //<-- $123.34
document.getElementById("price2").innerHTML = formatCurrency(123.34,"c","£"); //<-- £123.34
Here is the fiddle

Date extraction JavaScript for Acrobat does not work

Here's the breakdown:
What code do I need to extract the 12, 26, and 48 from a field whose value is 101219488926 and then display it in the format MM/DD/YY? (So in this case, the new value would need to be 12/26/48)
Here's the long version:
I'm using a mag-stripe reader that takes information from the swiped card (a driver license) and then uses that info to auto-populate certain fields in a PDF (first name, last name, date of birth, etc).
Everything works fine, with one exception: the date of birth. Even that does technically work, but the value is in this format (assuming the person's DOB is 26 December 1948):
101219488926
What I need is: the month (12), day (26), and year (1948) stripped out of that long number, then converted to display in the format MM/DD/YY
Outside of Acrobat, this seems to work just fine:
var dob = 101219488926;
trimmonth = dob.substring(2,4);
trimday = dob.substring(10,12);
trimyear = dob.substring(6,8);
dob.value = trimmonth + "/" + trimday + "/" + trimyear;
Any suggestions?
The code you have there shouldn't work - substring is a String function, so you would need to convert that number you have to a string for it to be available. Setting dob.value is also suspect, since dob is a Number, and numbers do not have a value property.
Of course, it's obvious that you're not showing the actual code you have tried, but something like this would probably work:
// Appending blank string to type coerce
var dob = 101219488926 + '';
// Array.join to glue the numbers together
// (no reason why you **have** to use this; the original method will work fine too)
dopInput.value = [dob.substring(2,4), dob.substring(10,12), dob.substring(6,8)].join('/');

Categories

Resources