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.
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.
var num = 1215464565;
var newNum = num.toString().match(/.{2}/g).join('-');
console.log(newNum);
Use the below regex in replace
function
(?!^)(\d{2})(?=(?:\d{2})*$)
and then replace the matched digits with -$1
> 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
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);