我有一串数字,应该有9个字符,我有一个正则表达式,用相同的字符串和一些空格替换字符串;像这样的东西:
TheString = '123456789';
TheSpacedString = TheString.replace(/(\d{1})(\d{2})(\d{2})(\d{2})(\d{2})/, '$1 $2 $3 $4 $5');
TheSpacedString format is now '1 23 45 67 89'
问题是,当字符串的长度不是9时,格式化不起作用:例如,如果我们有这个:
TheString = '12345';
TheSpacedString = TheString.replace(/(\d{1})(\d{2})(\d{2})(\d{2})(\d{2})/, '$1 $2 $3 $4 $5');
format should be '1 23 45'
但相反,字符串只是'12345'
。我的正则表达式有什么问题? jsFiddle是 here
答案 0 :(得分:4)
使用?
TheSpacedString = TheString.replace(/(\d{1})(\d{2})(\d{2})(\d{2})?(\d{2})?/, '$1 $2 $3 $4 $5');