Tuesday, March 27, 2018

javascript regular expression 常見的用法

(1) 全部取代「特定字串」
範例: 刪除所有的 a 字元
const s = 'abcdeabcdeabcde';
const r = s.replace(/(?:a)/g, '');

使用 non-capturing group 符號  ?: 

(2) 計算「特定字串」的所有出現次數
範例: 計算所有的 a 字元出現次數
const s = 'abcdeabcdeabcde';
const times = (s.match(/a/g) || []).length

(3) 比對所有符合的特定字串
範例: 找出所有的 abcdeabcde
const s = 'abcdeabcdeabcde';
const rr = s.match(/(abcde)\1/g);

使用 capturing group 和 back reference