正規表達式: 來搜尋或是取代字串的好工具
在 JavaScript 中可以透過 RegExp 物件以及 特定Method 來做字串處理的相關應用
正規表達式由 pattern 和 optional flags 組成
有兩種建立方式:
// 1. constructor function
regexp = new RegExp("pattern", "flags");
// 2. regular expression literal
// 用兩個斜線 / 包住 pattern
regexp = /pattern/; // no flags
regexp = /pattern/gmi; // with flags g,m and i (to be covered soon)
/.../ 的寫法,無法在 pattern 中置入變數,例如 ${...}
如果屬於較動態的規則,例如需依照使用者輸入的字串來進行搜尋,就可以使用 new RegExp
let tag = prompt("What tag do you want to find?", "h2");
let regexp = new RegExp(`<${tag}>`);
正規表達式的比對方式
常見有六種
i ignore case: 不分大小寫g global search: 搜尋整個字串,從第一個字元到最後一個m multiline search: 多行搜尋; 只會影響使用 ^ $ 的結果s dotall search: 讓 . 也能匹配到 \n換行符號u unicode searchy sticky search: 從指定位置搜尋str.match(regexp) 找出 regexp 是否匹配 str
match到,回傳 Array;反之回傳 null
let str = "We will, we will rock you";
// 1. 不使用 g, 回傳第一個匹配到結果以及相關資訊 (index, input, groups)
// 不分大小寫, 匹配到第一個 We
let result = str.match(/we/i);
// result = ['We', index: 0, input: 'We will, we will rock you', groups: undefined]
// 區分大小寫, 匹配到第二個 we
let result = str.match(/we/);
// result = ['we', index: 9, input: 'We will, we will rock you', groups: undefined]
// 2. 使用 g, 回傳所有匹配到的結果, 沒有相關資訊
let result = str.match(/we/ig);
// result = ['We', 'we']
str.replace(regexp, replacement) 取代匹配到的字串
alert( "We will, we will".replace(/we/i, "I") );
// I will, we will
replacement 還可以搭配用其他的 pattern
例如: $& 置入完整匹配到的字
alert( "I love HTML".replace(/HTML/, "$& and JavaScript") );
// I love HTML and JavaScript
regexp.test(str) 檢查字串是否符合正規表達式的 pattern,回傳 true or false
const str = 'hello world!';
const result = /^hello/.test(str);
console.log(result); // true
JAVASCRIPT.INFO - Regular expressions
MDN - Regular expressions