首页 > 解决方案 > 如何用新的另一个字符串和 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

标签: javascript

解决方案


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},将第二个参数更改为replacewith str2.padEnd(5, '0')

这个正则表达式匹配字符串的开头,然后使用插入花括号内的参数^匹配任何使用.精确length时间的字符。length


推荐阅读