5

I'm trying to convert a number like: 1215464565 into 12-15-46-45-65. I'm trying to do this:

var num = 1215464565; 
num = num.toString();
num.replace(/(.{2)/g,"-1");

The JSFiddle, however doesn't reflect this change though.

Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
user94628
  • 3,641
  • 17
  • 51
  • 88
  • `num = num.replace(/(.{2})/g,"-1");` – Regent Nov 13 '14 at 13:59
  • @Regent It won't work. – Avinash Raj Nov 13 '14 at 14:15
  • @AvinashRaj it works (all pairs of digits are replaced with "-1" in `1215464565`). If you ask what is the point to replace pairs of digits with "-1" while hyphens between pairs of digits are required - I don't know, I just fixed OP code line. – Regent Nov 14 '14 at 05:35

3 Answers3

16
var num = 1215464565; 
var newNum = num.toString().match(/.{2}/g).join('-');
console.log(newNum);

jsFiddle example

j08691
  • 204,283
  • 31
  • 260
  • 272
  • 1
    IMHO this is the most readable solution! +1 – Renato Gama Nov 13 '14 at 14:04
  • pretty cool, good to go! –  Aug 30 '17 at 02:50
  • 3
    This only works if `num` is exactly divisible by the split number otherwise the last block is missed off use `match(/.{1,2}/g` to ensure the last chars are shown. – chris Jan 12 '18 at 10:31
  • 1
    If the string is empty then this throws an error `match(/.{0,2}/g).join(' ').trim().replace(/\s/g, '-');` works for empty strings, one character strings and everything after that. But we are getting a bit verbose. – nidal Oct 09 '18 at 15:57
2

Use the below regex in replace function

(?!^)(\d{2})(?=(?:\d{2})*$)

and then replace the matched digits with -$1

DEMO

> var num = 1215464565;
undefined
> num = num.toString();
'1215464565'
> num.replace(/(?!^)(\d{2})(?=(?:\d{2})*$)/g, '-$1')
'12-15-46-45-65'

Regular Expression:

(?!                      look ahead to see if there is not:
  ^                        the beginning of the string
)                        end of look-ahead
(                        group and capture to \1:
  \d{2}                    digits (0-9) (2 times)
)                        end of \1
(?=                      look ahead to see if there is:
  (?:                      group, but do not capture (0 or more
                           times):
    \d{2}                    digits (0-9) (2 times)
  )*                       end of grouping
  $                        before an optional \n, and the end of
                           the string
)                        end of look-ahead
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

This should work for you:

var num = 1215464565; 
num = num.toString();
for(var i = 2; i < num.length; i = i + 2)
{
    num = [num.slice(0, i), "-", num.slice(i)].join('');
    i++;
}
window.alert("" + num);
brso05
  • 13,142
  • 2
  • 21
  • 40