โจทย์
String: 'My Name is John, Smith I live in US'
ต้องการลบข้อความหลัง comma และคำถัดไป ("I live in US") เหลือ: 'My Name is John, Smith'
วิธีทำ
ใช้ match() ร่วมกับ split()
ตัวอย่างโค้ด
var sentence = 'My Name is John, Smith I live in US';
console.log("The original value="+sentence);
var expression = sentence.match(/([^,]*)(.*)/)[1];
var positionForComma = sentence.match(/([^,]*),(.*)/)[2].split(' ')[1]
var newValue = expression + ', ' + positionForComma
console.log("Updated="+newValue);
วิธีรัน
node fileName.js
ชื่อไฟล์ demo175.js
ผลลัพธ์
PS C:\Users\Amit\javascript-code> node demo175.js The original value=My Name is John, Smith I live in US Updated=My Name is John, Smith
คำอธิบาย
match(/([^,]*)(.*)/)[1] จับข้อความก่อน comma แรกmatch(/([^,]*),(.*)/)[2].split(' ')[1] จับข้อความหลัง comma แล้ว split ด้วย space เอาคำที่ 2 (Smith)
รวมกันได้ผลลัพธ์ที่ต้องการ