สมมติเรามีสตริงต่อไปนี้ หนึ่งในนั้นเริ่มต้นด้วยเครื่องหมายคำถาม คือเครื่องหมายวรรคตอน
var sentence1 = 'My Name is John Smith.' var sentence2 = '? My Name is John Smith.'
เราต้องตรวจสอบว่าประโยคใดประโยคหนึ่งข้างต้นเริ่มต้นด้วยเครื่องหมายวรรคตอนหรือไม่ โค้ดสำหรับตรวจสอบมีดังนี้
ตัวอย่าง
var punctuationDetailsRegularExpression=/^[.,:!?]/ var sentence1 = 'My Name is John Smith.' var output1 = !!sentence1.match(punctuationDetailsRegularExpression) if(output1==true) console.log("This ("+sentence1+") starts with a punctuation"); else console.log("This ("+sentence1+") does not starts with a punctuation"); var sentence2 = '? My Name is John Smith.' var output2 = !!sentence2.match(punctuationDetailsRegularExpression) if(output2==true) console.log("This ( "+sentence2+") starts with a punctuation"); else console.log("This ( "+sentence2+" ) does not starts with apunctuation");
เพื่อรันโปรแกรมด้านบน คุณต้องใช้คำสั่งต่อไปนี้
node fileName.js.
ที่นี่ชื่อไฟล์ของผมคือ demo209.js
ผลลัพธ์
จะได้ผลลัพธ์ดังนี้
PS C:\Users\Amit\javascript-code> node demo209.js This (My Name is John Smith.) does not starts with a punctuation This ( ? My Name is John Smith.) starts with a punctuation