3月 12, 2020 Javascript

Regular Expression

我們常常會使用到 Regular Expression 來驗證字串的格式,由日期、電話號碼到特定的格式都可以用 Regular Expression 表達出來。而在 Javascript 中使用者可以使用 new RegExp() 來建立 Regular Expression 物件。

// create regexp object
var re1 = /^\d{4}-\d{2}-\d{2}$/i;
// create regexp object
var re2 = new RegExp('^\d{4}-\d{2}-\d{2}$', 'i');
console.log(re1.test('2019-11-22'));
// true
console.log(re2.test('2019-11-22'));
// true

它們的運作是一樣功能的。由上面的代碼推算出,我們可以透過使用 new RegExp() 來動態建立一個 Regular Expression Object。

// create regex by providing pattern string
const createRegExp = string => new RegExp('/^' + string + '$/');

產生問題

上面代碼雖然很方便,但是如果有使用者輸入了和 Regular Expression 相同的保留字,就會有可能把你的程式弄壞了 !!

// create regex
var re1 = createRegExp('*^*^*$*');

這樣就會把程式弄壞了。要防止這個情況,我們需要為傳入的參數 Escape 走 Regular Expression 的保留字。例如以下字符 :

\ ^ $ * + ? . ( ) | { } [ ]

我們可以寫一個 Function 把上面的字符 Escape,然後回傳出去。

/**
* escape regexp
*/
const escapeRegExp = string => {
// $& means the whole matched string
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
// example
escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");
// result
>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \]"

經過 Escape 後的字串就可以放心放到 new RegExp() 中使用,以產生 Regular Expression Object。

參考網址 : https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex

NPM Package

另外已經有大神把 Function 打包,放到 NPM 上去了,只要使用 NPM 下載就可以直接使用。

# npm install escape-string-regexp
過去文章
2025 年 (9)
04 月 (5)
03 月 (1)
02 月 (3)
2024 年 (25)
11 月 (3)
10 月 (3)
09 月 (1)
03 月 (18)
2022 年 (6)
10 月 (1)
06 月 (2)
05 月 (1)
03 月 (1)
01 月 (1)
2021 年 (21)
11 月 (7)
07 月 (1)
06 月 (2)
05 月 (2)
04 月 (6)
03 月 (2)
02 月 (1)
2020 年 (92)
12 月 (1)
11 月 (2)
10 月 (4)
09 月 (10)
08 月 (5)
07 月 (1)
06 月 (3)
05 月 (1)
04 月 (4)
03 月 (25)
02 月 (7)
01 月 (29)
2019 年 (57)
12 月 (25)
11 月 (7)
09 月 (25)