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

วิธีค้นหาและแสดงส่วน pathname ของ href ในแท็ก area ด้วย JavaScript

บทนำ

Property pathname ของ HTMLAreaElement ช่วยให้ดึงเฉพาะส่วนพาธ (path) ของ URL ในแอตทริบิวต์ href ได้ โดยไม่รวม protocol, domain, query string หรือ hash

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

<!DOCTYPE html>
<html>
<body>
  <img src="/images/html.gif" alt="HTML Map" border="0" usemap="#html"/>
  <map name="html">
    <area id="myarea" shape="circle" coords="154,150,59" 
          href="about.htm" target="_self">
  </map>
  <script>
    var x = document.getElementById("myarea").pathname;
    document.write("<br>Pathname: " + x);
  </script>
</body>
</html>

ผลลัพธ์

Pathname: /about.htm

คำอธิบาย

  • .pathname - คืนค่าพาธของ URL เริ่มต้นด้วย / เสมอ
  • หาก href เป็น relative path เช่น about.htm จะคืนค่า /about.htm
  • หาก href เป็น absolute URL เช่น https://example.com/path/page.html จะคืนค่า /path/page.html

เปรียบเทียบ URL Properties

สำหรับ URL: https://example.com:8080/path/page.html?query=1#section

Propertyผลลัพธ์
hrefhttps://example.com:8080/path/page.html?query=1#section
protocolhttps:
hostexample.com:8080
hostnameexample.com
port8080
pathname/path/page.html
search?query=1
hash#section