简体   繁体   中英

RegexExp not capturing group properly

I am trying to eliminate some characters if found in my string like v_[i] will be v.To do this I am using RegExp but it is not capturing the group.

var string='v_[i]';
var regexExp = new RegExp('_[\w+]','ig');
var finalstring = string.replace(regexExp,'');
alert(finalstring);

While in the other hand if i use a literal string it works perfectly

var finalstring = string.replace(/_\[\w+\]/ig,'');

then why RegExp not capturing the group as the literal string does.

You should escape the brackets in your regex:

var string = 'v_[i]';
var regexExp = /_\[\w+\]/ig;
var finalstring = string.replace(regexExp, '');

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