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

ความแตกต่างระหว่าง substr() และ substring() ใน JavaScript

ทั้งสองเมธอดดึง substring แต่ พารามิเตอร์ต่างกัน:

  • substring(start, end) – พารามิเตอร์ที่ 2 คือ index หยุด (ไม่รวม)
  • substr(start, length) – พารามิเตอร์ที่ 2 คือ ความยาว (จำนวนตัวอักษร)

หมายเหตุ: substr() เป็น legacy (deprecated ในบาง spec) ควรใช้ substring() หรือ slice() แทน

ตัวอย่าง substr()

<script>
var str = "Apples are round, and apples are juicy.";
document.write("(1,2): " + str.substr(1,2));      // "pp" (เริ่ม 1, ยาว 2)
document.write("<br />(-2,2): " + str.substr(-2,2)); // "y." (นับจากท้าย 2 ตัว, ยาว 2)
document.write("<br />(1): " + str.substr(1));       // "pples are round, and apples are juicy."
document.write("<br />(-20,2): " + str.substr(-20,2)); // "nd" (นับจากท้าย 20 ตัว)
document.write("<br />(20,2): " + str.substr(20,2));   // "ap" (เริ่ม 20, ยาว 2)
</script>

ตัวอย่าง substring()

<script>
var str = "Apples are round, and apples are juicy.";
document.write("(1,2): " + str.substring(1,2));    // "p" (index 1 ถึง 2 ไม่รวม)
document.write("<br />(0,10): " + str.substring(0,10)); // "Apples are"
document.write("<br />(5): " + str.substring(5));       // "s are round, and apples are juicy."
</script>

ความแตกต่างสำคัญเพิ่มเติม

แนะนำ: ใช้ slice()

str.slice(1, 3)   // "pp" (เหมือน substring แต่รองรับ negative index)
str.slice(-3)     // "cy." (3 ตัวท้าย)
คุณสมบัติsubstr()substring()
Negative startนับจากท้ายสตริงถือเป็น 0
start > endคืน "" (empty)สลับให้เอง (swap)
StandardLegacy (Annex B)ECMAScript standard