在JavaScript中以空格开头替换零
我们需要编写一个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
热门推荐
10 婚礼亲友祝福语简短幽默
11 生日祝福语古语简短创意
12 姥爷生日祝福语简短精辟
13 孩子满月随礼简短祝福语
14 给老师祝福语简短元旦
15 儿子31岁祝福语简短
16 恭喜新郎父母简短祝福语
17 生日祝福语短句简短霸气
18 弟弟的祝福语简短霸气