Regular Expression ដែលយើងអាចបកប្រែមកថា កន្សោមរូបមន្ត គឺជាពាក្យពេចន៍ដែលជារូបមន្តនៃការស្វែងរកនិងឬជំនួសតួអក្សរឬពាក្យទាំងឡាយនៅក្នុងប្រយោគផ្សេងៗ។ ទំរង់ទូទៅនៃកន្សោមរូបមន្ត គឺមានសណ្ឋានដូចនេះ /pattern/modifiers ឧទាហរណ៍ដូចជា /ITStepCambodia/i ជាដើម ដែលនៅក្នុងនោះ ITStepCambodia ជា រូបមន្ត ដែលជាពាក្យត្រូវស្វែងរកនិងឬជំនួស ហើយ i ជា កត្តាកំណត់ (modifier) ។
នៅក្នុងកម្មវិធីជាក់ស្តែង យើងអាចប្រើប្រាស់វិធីឈ្មោះ search() នៃថ្នាក់ string រួមជាមួយនឹងកន្សោមរូបមន្តណាមួយ នៅក្នុងការស្វែងរកពាក្យនិងឬ តួអក្សរផ្សេងៗ។ ពិនិត្យកម្មវិធីខាងក្រោមនេះ៖
លើសពីនេះទៀត យើងក៏អាចយកវិធីឈ្មោះ replace() នៃថ្នាក់ string មកប្រើជាមួយនឹងកន្សោមរូបមន្ត ក្នុងការជំនួសពាក្យឬតួអក្សរនៅក្នុងឃ្លាប្រយោគផ្សេងៗបានផងដែរ។
Regular Expression Modifiers
Modifier | Description |
---|---|
i | Perform case-insensitive matching |
g | Perform a global match (find all matches rather than stopping after the first match) |
m | Perform multiline matching |
Regular Expression Patterns
Expression | Description |
---|---|
[abc] | Find any of the characters between the brackets |
[0-9] | Find any of the digits between the brackets |
(x|y) | Find any of the alternatives separated with | |
\d | Find a digit |
\s | Find a whitespace character |
\b | Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b |
\uxxxx | Find the Unicode character specified by the hexadecimal number xxxx |
n+ | Matches any string that contains at least one n |
n* | Matches any string that contains zero or more occurrences of n |
n? | Matches any string that contains zero or one occurrences of n |
យ៉ាងណាម៉ិញ គ្រប់វត្ថុដែលជាកន្សោមរូបមន្ត គឺជាសិស្សនៃថ្នាក់ RegExp ។ ដូចនេះ យើងអាចយកវិធីមួយចំនួននៅក្នុងថ្នាក់នេះមកប្រើប្រាស់ មានដូចជាវិធីឈ្មោះ test() ជាដើម ដែលយើងអាចយកវាមកប្រើក្នុងការពិនិត្យមើលថា តើនៅក្នុងឃ្លាប្រយោគណាមួយ ពិតជាមានពាក្យនិងឬតួអក្សរដូចនៅក្នុងរូបមន្តរបស់កន្សោមរូបមន្តណាមួយដែរឬយ៉ាងណា។ វិធីឈ្មោះ test() នេះផ្តល់លទ្ធផលជាតក្កអថេរ true ឬ false ៕
var patt = /e/; patt.test("The best things in life are free!");Complete JavaScript RegExp Reference