开发者

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 ne开发者_StackOverflow中文版w_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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜