简体   繁体   中英

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

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');

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM