admin管理员组文章数量:1435534
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?
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?
Share Improve this question edited Apr 4, 2015 at 7:53 Wiktor Stribiżew 628k41 gold badges498 silver badges616 bronze badges asked Apr 4, 2015 at 6:29 Syed Sabhi XaidiSyed Sabhi Xaidi 111 gold badge2 silver badges7 bronze badges 3- 35200123456785 this is my input – Syed Sabhi Xaidi Commented Apr 4, 2015 at 6:52
-
do u need an
-
after 5 and 8 digits? – Rajeshwar Commented Apr 4, 2015 at 7:17 -
1
Try this regex
(\d{5})(\d{8})(\d{1})
and then replace function like follow$1-$2-$3
Demo: regex101./r/fR6tX1/1 – Amen Jlili Commented Apr 4, 2015 at 7:39
2 Answers
Reset to default 1You 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 end
Replacement 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"/>
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
本文标签: regexRegular Expression to add dashes to a phone number in JavaScriptStack Overflow
版权声明:本文标题:regex - Regular Expression to add dashes to a phone number in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745631592a2667307.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论