用空格替代 JavaScript 中以 0 开头的数字
我们需要编写一个 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP