Application and summary of ES6 regular rules

1. RegExp constructor

In ES5, there are two situations for the parameters of the RegExp constructor.

The first case is that the parameter is a string, in which case the second parameter represents the modifier (flag) of the regular expression.

var regex = new RegExp('xyz', 'i');
// 等价于
var regex = /xyz/i;

The second case is that the parameter is a regular expression, in which case a copy of the original regular expression will be returned.

var regex = new RegExp(/xyz/i);
// 等价于
var regex = /xyz/i;

However, ES5 does not allow you to use the second parameter and add modifiers at this time, otherwise an error will be reported.

var regex = new RegExp(/xyz/, 'i');
// Uncaught TypeError: Cannot supply flags when constructing one RegExp from another

ES6 changes this behavior. If the first parameter of the RegExp constructor is a regular object, you can use the second parameter to specify the modifier. Moreover, the returned regular expression will ignore the modifiers of the original regular expression and only use the newly specified modifiers.

new RegExp(/abc/ig, 'i').flags
// "i"

In the above code, the modifier of the original regular object is igthat it will be overwritten by the second parameter i.

Guess you like

Origin blog.csdn.net/yu1431/article/details/132359850