ใช้ Regex พร้อม Flag g (Global) เพื่อหาค่าที่ตรงกันทั้งหมด
ตัวอย่างโค้ด
function checkMultipleOccurrences(sentence) {
var matchExpression = /(JavaScript?[^\s]+)|(typescript?[^\s]+)/g;
return sentence.match(matchExpression);
}
var sentence = "This is my first JavaScript Program which is the subset of typescript";
console.log(sentence);
console.log(checkMultipleOccurrences(sentence));
วิธีรันโปรแกรม
ใช้คำสั่ง node fileName.js (เช่น node demo70.js)
ผลลัพธ์
This is my first JavaScript Program which is the subset of typescript
[ 'JavaScript', 'typescript' ]