如何用空格替换前导零

时间:2018-07-30 11:32:49

标签: javascript

我需要用javascript函数中的数字替换前导零。需要确保保留前面的空格。例如如果我的字符串值定义为" 004590808",那么我的输出应为 " 4590808"。 预先感谢...。

2 个答案:

答案 0 :(得分:0)

您可以使用需要替换所需长度的函数。

var string = '   004590808',
    replaced = string.replace(/^\s*0+/, ({ length }) => ' '.repeat(length));
    
console.log(string);
console.log(replaced);

答案 1 :(得分:0)

您的问题不清楚,因为您没有将字符串包装在反引号中

我们需要该函数,因为正则表达式会找到两个00,并且需要将其转换为任意长度(此处为空格)。我使用“ *”表示可见性

var s = "   004590808";
s = s.replace(/^\s+0+/,function (z) { return z.replace(/0/g,"*")});

console.log(
  ">" +
  s +
  "<", s.length);

相关问题