Javascript String format

So, I have few lines for tests:

Test: '00 -44 48 5555 8361 'Expected: 004-448-555-583-61

Test: '0 - 22 1985--324' Expected: 022-198-53-24

Test: '555372654' Expected: 555-372-654

Any suggestions would be helpful. I've spent hours trying to figure out why some of the expected results work and others don't. If string S represents a telephone number, the string must be reformatted. String S consists of N characters: numbers, spaces and / or dash. It contains at least two digits. Spaces and dashes in the S string can be ignored. I want to reformat the given phone number so that the digits are grouped into blocks of length 3, separated by single strokes. If necessary, the last block or the last two blocks can be two in length.

var s = "00-44  48 5555 8361";
var n = s.replace(/\D/g,'');
var temp = formatNumber(n);
var final = temp.replace(/\-$/,'');
alert(final);

function formatNumber(S){
  var len = S.length;
  var max = len - 2 * ((3-len) % 3);
  var dash = "-";
  var result;
  for(i = 0; i < max; i+=3){
  	result += S.substring(i, i+3).concat(dash);
  }
  for(i = max; i < len; i+=2){
  	result += S.substring(i, i+2).concat(dash);
  }
	return result.toString();
}
      

Run codeHide result


+3


source to share


5 answers


You may try:



var phones = [
  '00-44 48 5555 8361',
  '0 - 22 1985--324',
  '555372654'
];

phones = phones.map(function(phone) {
    var num = phone.replace(/\D/g, '');
    return num.replace(/(...?)(?!.?$)/g, '$1-');
});

console.log(phones);
      

Run codeHide result


+2


source


In a string, var max = len - 2 * ((3-len) % 3);

you are actually adding to len

without subtracting as you expect (because len >= 3

in 3 - len <= 0

this way (3 - len) % 3 <= 0

, so when multiplied by the -2

result will be positive), thus max

always equal to or greater than the length len

.

Try the following:

max = len - (len % 3? ((len + 1) % 3? 4: 2): 0);

      

which can be explained:



var max = len;
if(len % 3 === 0) {               // if len is divisible by 3 (if len === 0, 3, 6, 9, ...)
    max -= 0;                     // substract 0 (leave max === len)
} else {                          // if len is not divisible by 3
    if((len + 1) % 3 === 0) {     // if len + 1 is divisible by 3 (if len === 2, 5, 8, 11, ...)
        max -= 2;                 // substract 2 (only one part containing 2 digits)
    } else {                      // if len === 1, 4, 7, 10, ...
        max -= 4;                 // substract 4 (two parts containing 2 digits)
    }
}

      

function formatNumber(s) {
  var l = s.length,
      max = l - (l % 3? ((l + 1) % 3? 4: 2): 0);
  var result = "";
  for(var i = 0; i < max; i+=3) {
    result += s.slice(i, i + 3) + "-";         // no need for concat just add "-" to the result of slice
  }
  for(var i = max; i < l; i+=2) {
    result += s.slice(i, i + 2) + "-";
  }
  return result.slice(0, -1);                   // the same as result.slice(0, result.length - 1) to remove the last '-'
}

console.log(formatNumber("123456789"));
console.log(formatNumber("12345678"));
console.log(formatNumber("1234567890"));
      

Run codeHide result


0


source


It seems that you always need this format (\d{3}-)+

.

function formatter(input) {
  return input
    
    // rm ws
    .replace(/\s+/g, '')
    
    // rm dashes
    .replace(/-/g, '')
    
    // split by 3 chars
    .split(/(.{3})/)
    
    .filter(g => g)
    
    .join('-')
  ;
}


var raw = [
  "00-44  48 5555 8361",
  "555372654",
  "0 - 22 1985--324"
];

console.log('Formatted', raw.map(formatter));
      

Run codeHide result


0


source


var n = '00-44 48 5555 8361';

console.log(formatPhone(n, 3));

function formatPhone(num, spacing) {
    num = (num+'').replace(/[^\d]/g, '').split('');

    return num.map(function (currentValue, index) {
        // Plus 1 because it 0-indexed.
        return (index + 1) % spacing === 0 
                 ? currentValue + '-' 
                 : currentValue
        ;
    }).join('');
}

      

https://jsfiddle.net/efpy3vLn/

0


source


You can do everything just by replacing the regex:

// Initial string
var s0 = "00-44  48 5555 8361";

// Remove everything that not a number
var s1 = s0.replace(/[^0-9]/g,'');

// A dash every three numbers
var s2 = s1.replace(/(...)/g,'$1\-');

// Remove the traling slash if any
var s3 = s2.replace(/\-$/,'');

      

0


source







All Articles