การ Parse URL
Parse URL ใน JavaScript ง่ายด้วย DOM method ไม่ต้องใช้ Regular Expressions ที่ซับซ้อน แค่เรียกฟังก์ชันเดียวคืนค่า parsed URL
ตัวอย่าง: สร้างฟังก์ชัน สร้าง anchor tag "a" ด้วย DOM method กำหนด URL ให้ anchor ด้วย href ฟังก์ชันคืนค่าส่วนต่างๆ ของ URL ที่ parsed แล้ว ใช้ JSON.stringify() แสดงผล
ตัวอย่าง
<html> <body> <script>
function URL(url) {
var urlParser = document.createElement('a');
urlParser.href = url;
return {
protocol: urlParser.protocol,
host: urlParser.host,
hostname: urlParser.hostname,
port: urlParser.port,
pathname: urlParser.pathname,
search: urlParser.search,
hash: urlParser.hash
};
}
document.write(JSON.stringify(URL("https://www.youtube.com/watch?v=tNJJSrfKYwQ")));
</script> </body> </html>
ผลลัพธ์
{"protocol":"https:","host":"www.youtube.com","hostname":"www.youtube.com","port":"","pathname":"/watch","search":"?v=tNJJSrfKYwQ","hash":""}