javascript - RegExp with square brackets replacing everything - Stack Overflow

I'm trying to replace all instances of [1] (including the brackets), but instead of replacing all

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
Add a ment  | 

4 Answers 4

Reset to default 5

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

[] 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+'\]')

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744102097a4558579.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信