简体   繁体   English

用方括号替换所有内容的正则表达式

[英]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 .我正在尝试替换[1]的所有实例(包括括号),但不是替换[1]的所有实例,而是替换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.由于您正在编写 Javascript 字符串文字,因此您需要编写\\来为正则表达式转义创建一个反斜杠。

Try escaping the brackets试试 escaping 的支架

var regexp = new RegExp('\\[' + index + '\\]', 'g');

[] is special in a regex. []在正则表达式中很特殊。 It defines a character class.它定义了一个字符 class。 For example:例如:

/[a-z]/

matches any letter, a through z .匹配任何字母,从 az Or:或者:

/[123abc]/

matches 1 , 2 , 3 , a , b , or c .匹配123abc

So your regex:所以你的正则表达式:

/[1]/

Means to match any character of 1 .表示匹配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.我更改了代码的最后一行,因为它确实更改了所有 [1],只是在替换 function 中添加了括号。 And also escape your brackets并且还逃避你的括号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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