Reputation: 11
function convertToValidPhoneNumber(text) {
var result = [];
text = text.replace(/^\d{2}-?\d{3}-?\d{3}-?\d{3}$/, "");
while (text.length >= 6){
result.push(text.substring(0, 3));
text = text.substring(3);
}
if (text.length > 0) result.push(text);
return result.join("-");
}
I test this function against 35200123456785
input string.
It gives me like a number like 352-001-234-56785
but I want 35200-12345678-5
.
What do I need to do to fix this?
Upvotes: 1
Views: 12960
Reputation: 31
number = this.state.number;
var expression = /(\D+)/g;
var npa = "";
var nxx = "";
var last4 = "";
number = number.toString().replace(expression, "");
npa = number.substr(0, 3);
nxx = number.substr(3, 3);
last4 = number.substr(6, 4);
number = npa + "-" + nxx + "-" + last4
Upvotes: 0
Reputation: 627126
You can use this updated function that uses ^(?=[0-9]{11})([0-9]{5})([0-9]{8})([0-9])$
regex:
^
- String start(?=[0-9]{11})
- Ensures there are 11 digits in the phone number([0-9]{5})
- First group capturing 5 digits([0-9]{8})
- Second group capturing 8 digits([0-9])
- Third group capturing 1 digit$
- String endReplacement string - "$1-$2-$3"
- uses back-references to those capturing groups in the regex by numbers and adds hyphens where you need them to be.
In case you have hyphens inside the input string, you should remove them before.
function convertToValidPhoneNumber(text) {
return text = text.replace(/-/g,"").replace(/^(?=[0-9]{11})([0-9]{5})([0-9]{8})([0-9])$/, "$1-$2-$3");
}
document.getElementById("res").innerHTML = convertToValidPhoneNumber("35200123456785") + " and " + convertToValidPhoneNumber("35-200-123-456-785");
<div id="res"/>
Upvotes: 1