简体   繁体   中英

Regular Expression to add dashes to a phone number in JavaScript

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?

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 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM