Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegExp with square brackets replacing everything

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+']')
like image 395
Shpigford Avatar asked Jul 06 '11 02:07

Shpigford


Video Answer


3 Answers

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.

like image 127
SLaks Avatar answered Oct 11 '22 16:10

SLaks


Try escaping the brackets

var regexp = new RegExp('\\[' + index + '\\]', 'g');
like image 39
bbg Avatar answered Oct 11 '22 15:10

bbg


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

like image 1
qwertymk Avatar answered Oct 11 '22 16:10

qwertymk