在每个第n个字符后插入字符

时间:2014-11-13 13:57:30

标签: javascript regex

我试图将数字转换为1215464565到12-15-46-45-65。我试图这样做:

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

然而,JSFiddle并没有反映出这种变化。

3 个答案:

答案 0 :(得分:15)

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

<强> jsFiddle example

答案 1 :(得分:1)

replace函数

中使用以下正则表达式
(?!^)(\d{2})(?=(?:\d{2})*$)

然后用-$1

替换匹配的数字

DEMO

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

正则表达式:

(?!                      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

答案 2 :(得分:1)

这应该适合你:

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