我在下面有一个简单的 Javascript 函数来替换前 16 个字符:
export const replaceFirstN = (str, n) => {
const replace = /^.{1,16}/
const re = new RegExp(replace)
return str.replace(re, m => "X".repeat(m.length))
}
现在,我想使用 n 参数,以便我可以控制可由 X 替换的字符数。我尝试将替换值更改为:
replace = "/^.{1,"+n+"}/"
还有各种变体,但不起作用。
有什么想法吗?
答案 0 :(得分:2)
const replaceFirstN = (str, n) => {
const re = new RegExp(`^.{1,${n}}`);
return str.replace(re, m => "X".repeat(m.length));
};
console.log(replaceFirstN("ruuuuuuuuuuuuuuuuuuuuuuun", 16));
console.log(replaceFirstN("apple", 2));
console.log(replaceFirstN("orange", 4));
答案 1 :(得分:2)
你不需要正则表达式,如果你只想替换字符串的前 n 个字符,你可以使用这样的东西:
const str = 'a sample test text to replace'
const replaceFirstN = (str = '', n) => {
const replacement = 'X'.repeat(n);
const rest = str.slice(n)
return replacement + rest;
}
console.log(replaceFirstN(str, 4))
>>> 'XXXXmple test text to replace'
您将动态构建的替换文本附加到字符串的其余部分。