JavaScript ရှိ Regular Expression အသုံးပြုမှုကို ပိုမိုကောင်းမွန်အောင်ပြုလုပ်ခြင်း
Regular Expression များသည် အလွန်လေးလံပြီး အတော်အသင့်နှေးကွေးစွာ အလုပ်လုပ်သောအရာဖြစ်သည်။ အခြားရွေးချယ်စရာ ဖြေရှင်းနည်းရှိပါက၊ �ိုအရာကိုပဲ အသုံးပြုသင့်သည်။
ဥပမာတစ်ခုကို ကြည့်ကြပါစို့။ ကြိုက်နှစ်သက်ရာ string တစ်ခုသည် အမေးသံသင်္ကေတ (exclamation mark) နှင့် စသလားဆိုတာ စစ်ဆေးရန်လိုအပ်သည်ဆိုပါစို့။ ကုဒ်ရေးသူတစ်ဦးက ဒီပြဿနာကို regular expression ဖြင့် ဖြေရှင်းခဲ့သည်။
let str = '!123';
if (/^!/.test(str)) {
console.log('+++');
} else {
console.log('---');
}
သို့သော်လည်း၊ ထိုကဲ့သို့သောအလုပ်သည် ပိုမိုမြန်ဆန်စွာ အလုပ်လုပ်သော ဖြေရှင်းနည်းရှိပါသည်။
let str = '!123';
if (str[0] == '!') {
console.log('+++');
} else {
console.log('---');
}
အောက်ပါကုဒ်သည် string အတွင်း
'33' ဆိုသည့် substring ပါရှိမှုကို စစ်ဆေးနေသည်။
ပိုမိုကောင်းမွန်အောင်ပြုလုပ်ပါ။
let str = '123345';
if (/33/.test(str)) {
console.log('+++');
} else {
console.log('---');
}
အောက်ပါကုဒ်သည် string ကို
'.html' ဖြင့် အဆုံးသတ်ထားခြင်း ရှိ၊မရှိ စစ်ဆေးနေသည်။
ပိုမိုကောင်းမွန်အောင်ပြုလုပ်ပါ။
let str = 'index.html';
if (/\.html$/.test(str)) {
console.log('+++');
} else {
console.log('---');
}
အောက်ပါကုဒ်သည် နောက်ဆုံးမှ space များကို �ြတ်တောက်ပစ်သည်။ ပိုမိုကောင်းမွန်အောင်ပြုလုပ်ပါ။
let str = ' text ';
let res = str.replace(/^\s+|\s+$/g, '');
console.log(res);