Reputation: 61
I'm working on angularJS:
I have an input field will can receive 10 numbers; and I store this number into a $scope.
In other part of myApp I will take this number and send it to a service. But before send, I have to split it number in two. The first 3 must be the area code, and the rest 7 must be the country code.
Upvotes: 1
Views: 2279
Reputation: 19228
Consider doing a positive lookahead regular expression (?=)
to make sure the input has 10 digits.
Then capture the digits into 2 separate groups by doing (\d{x})
where x is the number of digits you want.
Example:
"use strict";
let match = /(?=\d{10})(\d{3})(\d{7})/.exec("9994567890");
if (match) {
let area = match[1];
let country = match[2];
console.log("Area code is: " + area);
console.log("Country code is: " + country);
}
else {
console.log("Invalid phone number.")
}
Upvotes: 1
Reputation: 1463
Plain Javascript:
var input = "0123456789";
var area = input.substring(0, 3);
var country = input.substring(3, 10);
Upvotes: 2