Basically, inside a string template, the character \
must be escaped, being written as \\
. See the difference:
let current_counter = 1;
console.log(`/\[${current_counter}\]/g`); // imprime "/[1]/g"
console.log(`/\\[${current_counter}\\]/g`); // imprime "/\[1\]/g"
But that alone is not enough. /[1]/g
is the literal form of a regular expression: the bars at the beginning and end are delimiters and are not part of the regex itself, and the g
is one of many flags that can be used to change the behavior of the same (in this case, in a replace
it serves to replace all occurrences, so in your case it does not seem to be really necessary, since you just want to replace an occurrence).
Only in your case, you need to dynamically assemble a string that corresponds to an expression, so the way to do this is by passing the string to the constructor of RegExp
. The difference is that in this case the string should not have the bars at the beginning and end, and the flag g
is passed separately in the second parameter:
let current_counter = 1;
let regex = new RegExp(`\\[${current_counter}\\]`, 'g');
let novo_valor = 'teste[1]'.replace(regex, `[${current_counter + 1}]`);
console.log(novo_valor); // teste[2]
But because you want to replace
"[N]"
for"[N]"
... Would not replace"[0]"
for"[N]"
?– fernandosavio
@fernandosavio made the correction in the code.
– marcelo2605
Pq does not arrow the input name with
$(seletor).attr('name', 'order-recipient-name['+new_counter+']')
? I think it would be simpler.– Sam
@Sam because they are various inputs with patterns of different names.
– marcelo2605