I have this code .replace(/^(\d{0,3})(\d{0,2})/, '($1) $2');
.
I want to pass variable to make 3 dynamic.
I tried .replace(/^(\d{0,code.length})(\d{0,2})/, '($1) $2');
Thank you.
CodePudding user response:
You can use RegExp
to fill your parameters up
const code = {
length: 3
}
const regex = new RegExp(`^(\d{0,${code.length}})(\d{0,2})`)
console.log(regex)
CodePudding user response:
You can use concat regexp string with your variable like this
function replaceSymbols (str, symbols) {
const regexp = new RegExp('12' symbols, 'g')
return str.replace(regexp, '-replace_string-')
}
const str = '123456'
console.log(replaceSymbols(str, ''));
console.log(replaceSymbols(str, '34'));
console.log(replaceSymbols(str, '345'));