javascript - 如何用新的另一个字符串和 javascript 中的填充替换字符串的前 5 个字符?
问题描述
如果我有一个字符串需要用新字符串替换前 5 个字符并用 0 填充,那么最好的方法是什么?
前任:
const str1="jsdf532903043900934";
const str2= "21";
\\replace str1 with str2 "21" plus 3 zeros on the right
\\new string should be 2100032903043900934
解决方案
const str1 = "jsdf532903043900934";
const str2 = "21";
const result = replace(str1, str2, "5");
console.log(result);
function replace(str1, str2, length) {
const pattern = new RegExp(`^.{${length}}`);
return str1.replace(pattern, str2.padEnd(length, '0'));
}
我让这个例子接受了一个length
参数,所以如果需要的话改变长度会更容易。如果不需要,您可以将其删除并将表达式更改为^.{5}
,将第二个参数更改为replace
with str2.padEnd(5, '0')
。
这个正则表达式匹配字符串的开头,然后使用插入花括号内的参数^
匹配任何使用.
精确length
时间的字符。length
推荐阅读
- php - CSS问题排队菜单
- python - 如何只读取文件的一部分 Python
- ios - Xcode 12 在 Mac OS 10.15.4 中意外退出
- reactjs - 无法读取 null 的属性“公司”
- c++ - (C++) 为什么不计算文本文件中的额外空行?
- javascript - 如何以编程方式判断两个绝对定位的元素是否重叠?
- angularjs - 您无权访问此资源 [在 apache 上部署 Angular 时]
- php - 获取php输入值
- python - 如何优化 Python 代码以使用多处理
- python - 为什么 python 中的相同代码需要很长时间,但在 C 中运行速度很快