Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ตรวจสอบ URL เป็น Absolute หรือ Relative - JavaScript

ใช้ Regular Expression ทดสอบว่า URL เริ่มต้นด้วย https:// หรือ https:// หรือไม่

ตัวอย่างโค้ด

var regularExpressionForURL = /^https?:\/\//i;
var originalURL1 = "https://www.example.com/index";
var originalURL2 = "/index";

if (regularExpressionForURL.test(originalURL1)) {
  console.log("This is absolute URL");
} else {
  console.log("This is relative URL");
}

if (regularExpressionForURL.test(originalURL2)) {
  console.log("This is absolute URL");
} else {
  console.log("This is relative URL");
}

รันด้วยคำสั่ง:

node fileName.js

ชื่อไฟล์: demo266.js

ผลลัพธ์

PS C:\Users\Amit\javascript-code> node demo266.js
This is absolute URL
This is relative URL

คำอธิบาย: Regex ^https?:\/\//i ตรวจสอบว่าเริ่มต้นด้วย https:// หรือ https:// (case-insensitive) test() คืนค่า true/false