Skip to content

Instantly share code, notes, and snippets.

@veritymissed
Created August 13, 2019 11:02
Show Gist options
  • Save veritymissed/72dfb6a14eab616949e2211590c2c05e to your computer and use it in GitHub Desktop.
Save veritymissed/72dfb6a14eab616949e2211590c2c05e to your computer and use it in GitHub Desktop.
js regular expression 筆記

Regular expression in JS

Flag

接在Regx後面,語法為

_ /pattern/flags _

/g 全域搜尋,會掃完整個input,不會只看一行

/i 忽略大小寫

綜合在一起使用: /gi 忽略大小寫,並全域搜尋

/m multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)

/s "dotAll"; allows . to match newlines

/u Unicode; treat pattern as a sequence of Unicode code points (see also Binary strings)

/y sticky; matches only from the index indicated by the lastIndex property of this regular expression in the target string (and does not attempt to match from any later indexes).

/pattern/flags new RegExp(pattern[, flags]) RegExp(pattern[, flags])

var regex1 = /\w+/;
var regex2 = new RegExp('\\w+');

console.log(regex1);
// expected output: /\w+/

console.log(regex2);
// expected output: /\w+/

console.log(regex1 === regex2);
// expected output: false


/ab+c/i;
new RegExp(/ab+c/, 'i'); // literal notation
new RegExp('ab+c', 'i'); // constructor

var re = /\w+/;
var re = new RegExp('\\w+');

var re = /(\w+)\s(\w+)/;
var str = 'John Smith';
var newstr = str.replace(re, '$2, $1');
console.log(newstr);

var text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end';
var lines = text.split(/\r\n|\r|\n/);
console.log(lines); // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ]

var s = 'Please yes\nmake my day!';
s.match(/yes.*day/);
// Returns null
s.match(/yes[^]*day/);
// Returns ["yes\nmake my day"]

var str = '#foo#';
var regex = /foo/y;

regex.lastIndex = 1;
regex.test(str); // true
regex.lastIndex = 5;
regex.test(str); // false (lastIndex is taken into account with sticky flag)
regex.lastIndex; // 0 (reset after match failure)

var text = 'Образец text на русском языке';
var regex = /[\u0400-\u04FF]+/g;

var match = regex.exec(text);
console.log(match[0]);        // logs 'Образец'
console.log(regex.lastIndex); // logs '7'

var match2 = regex.exec(text);
console.log(match2[0]);       // logs 'на' [did not log 'text']
console.log(regex.lastIndex); // logs '15'

// and so on

var url = 'http://xxx.domain.com';
console.log(/[^.]+/.exec(url)[0].substr(7)); // logs 'xxx'

與 replace 搭配使用

str.replace(regexp|substr, newStr|function);

str.replacce('/s*/g', "") 搜尋整個字串的空白,並刪除

RegExp Object 正規表達式物件

References

String.prototype.replace() on MDN

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment