I'm trying to replace all instances of [1]
(including the brackets), but instead of replacing all instances of [1]
, it's replacing all instances of 1
.
var index = 'abc123'
var regexp = new RegExp('[' + index + ']', 'g');
var new_id = new Date().getTime();
$(this).html().replace(regexp,'['+new_id+']')
You need to escape the brackets with \\
characters.
Since you're writing a Javascript string literal, you need to write \\
to create a single backslash for the regex escape.
Try escaping the brackets
var regexp = new RegExp('\\[' + index + '\\]', 'g');
Try this:
var index = 'abc123'
var regexp = new RegExp('\\[' + index + '\\]', 'g');
var new_id = new Date().getTime();
$(this).html().replace(regexp,new_id)
I changed the last line of your code because it did change all [1]'s just added the brackets back in the replace function. And also escape your brackets
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With