如何用空格替换前导零 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/31 22:04: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

相关文章


有用资源