如何用Javascript编译动态正则表达式



下面有一个简单的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+"}/"

还有各种各样的变化,但它不起作用。

知道吗?

使用Template literals

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));

您不需要regex,如果您只想替换字符串的前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'

其中,将动态构建的替换文本与字符串的其余部分一起追加。

最新更新