Skip to content Skip to sidebar Skip to footer

Insert Character After Every Nth Character

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,

Solution 1:

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

jsFiddle example

Solution 2:

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

Solution 3:

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 donot capture (0or 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

Post a Comment for "Insert Character After Every Nth Character"