1. RegExp constructor
es5 writing:
var regex = new RegExp('xyz', 'i' ); // equivalent to var regex = /xyz/ i; var regex = new RegExp(/xyz/ i); // equivalent to var regex = /xyz/i;
es6 writing:
var regex = new RegExp(/xyz/, 'i');
2. Regular method for strings
String objects have 4 methods that can use regular expressions: match()
, replace()
, search()
andsplit()。
ES6 uses these four methods RegExp
as instance methods that are all called within the language, so that all regular-related methods are defined on the RegExp
object.
String.prototype.match 调用 RegExp.prototype[Symbol.match]
String.prototype.replace 调用 RegExp.prototype[Symbol.replace]
String.prototype.search calls RegExp.prototype[Symbol.search]
String.prototype.split calls RegExp.prototype[Symbol.split]
3. Lookbehind assertions
es5 lookahead assertion:
Lookahead assertion: x(?=y) (x only matches before y)
/\d+(?=%)/.exec('100% of US presidents have been male') // ["100"] Lookahead Negative Assertion: /x(?!y)/(x can only match if it is not in front of y) /\d+(?!%)/.exec('that’s all 44 of them') // ["44"]
es6 lookbehind assertion:
Line-behind assertion: /(?<=y)x/ matches only the digits after the dollar sign, which should be written as/(?<=\$)\d+/
Negative assertion after the line: /(?<!y)x/ For example, to match only numbers that are not after the dollar sign, write it as /(?<!\$)\d+/
.
/(?<=\$)\d+/.exec('Benjamin Franklin is on the $100 bill') // ["100"] /(?<!\$)\d+/.exec('it’s is worth about €90') // ["90"]
The following example is a string replacement using a lookbehind assertion.
const reg= /(?<=\$)foo/g; '$foo %foo foo'.replace(reg, 'bar'); // '$bar %foo foo'
In the above code, only after the dollar sign foo
will be replaced.