สมมติว่ามี URL:
https://www.tutorialspoint.com/advanced_microsoft_word_2013_tutorial/index.asp
ต้องการดึงเฉพาะส่วนท้าย index.asp ใช้ replace() พร้อม Regular Expression
ตัวอย่างโค้ด
var url = "https://www.tutorialspoint.com/advanced_microsoft_word_2013_tutorial/index.asp";
var getValues = url.replace(/^.*\//, '');
console.log("The original value = " + url);
console.log("New Value = " + getValues);รันด้วยคำสั่ง:
node fileName.js
ชื่อไฟล์: demo258.js
ผลลัพธ์
PS C:\Users\Amit\javascript-code> node demo258.js The original value = https://www.tutorialspoint.com/advanced_microsoft_word_2013_tutorial/index.asp New Value = index.asp
คำอธิบาย Regex: ^.*\/ จับข้อความตั้งแต่ต้นจนถึง slash สุดท้าย แล้วแทนที่ด้วยสตริงว่าง