RegExp in JS

Literal

/patter/attributes

new RegExp

new RegExp(pattern, attribtues)

pattern

RegExp Attribtues

  • g: global
  • i: ignoreCase
  • m: multi-lines
  • source: literal text
  • lastIndex: mark the index where to start next match

Example

var re = new RegExp('^[0-9]+$','g');
console.log(re.source); //^[0-9]+$
`</pre>

<pre>`var re = new RegExp('\\d{3}','g');
var str = '123a456b';
console.log(re.lastIndex); // 0
re.exec(str); //return ['123']
console.log(re.lastIndex); // 3
re.exec(str); // ['456']
console.log(re.lastIndex); //7
re.exec(str);
console.log(re.lastIndex) // 0, reset to 0 if exceed.
re.lastIndex = 3; //Set Start Index
re.exec(str); // ['456']

RegExp Methods

re.compile(re) //execute RegExp in scripts
re.exec(str) //return an Array including String, or null.
re.test(str) => true/false

String Methods

str.search(re,subStr)
str.match(re) => Array including String
str.replace(re,str) => new String
str.split(re)

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×