Regular Expression

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