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+']')
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+']')
Share
Improve this question
asked Jul 6, 2011 at 2:59
ShpigfordShpigford
25.4k61 gold badges167 silver badges262 bronze badges
1
-
escape the specials, bro.
[]
is a range selector, like[a-z]
– vol7ron Commented Jul 6, 2011 at 3:12
4 Answers
Reset to default 5You 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
[]
is special in a regex. It defines a character class. For example:
/[a-z]/
matches any letter, a through z. Or:
/[123abc]/
matches 1, 2, 3, a, b, or c.
So your regex:
/[1]/
Means to match any character of 1.
What you need to do is escape the [ and ] like so:
/\[1\]/
Or specifically in your code:
$(this).html().replace(regexp,'\['+new_id+'\]')