在 JavaScript 中用空格替换开头的零

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/9 1:48:17

我们需要编写一个 JavaScript 函数,该函数接受一个表示数字的字符串。

用空格替换数字中的前导零。确保保留数字中的前导空格。

例如:如果字符串值定义为 −

"004590808"

然后输出应为 −

"4590808"

示例

其代码为 −

const str = ' 004590808';
const replaceWithSpace = str => {
   let replaced = '';
   const regex = new RegExp(/^\s*0+/);
   replaced = str.replace(regex, el => {
      const { length } = el;
      return ' '.repeat(length);
   });
   return replaced;
};
console.log(replaceWithSpace(str));

输出

控制台中的输出将是 −

4590808

相关文章


有用资源