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

วิธีหาตำแหน่งแรก (First Index) ของค่าในสตริง JavaScript

ใช้เมธอด indexOf() หาตำแหน่งแรกที่พบค่าที่ค้นหาในสตริง คืน -1 ถ้าไม่พบ

ตัวอย่าง

<html>
  <head>
    <title>JavaScript String indexOf() Method</title>
  </head>
  <body>
    <script>
      var str = new String("Learning is fun! Learning is sharing!");
      var index = str.indexOf("Learning");
      document.write("First index of 'Learning': " + index); // 0
    </script>
  </body>
</html>

Syntax

string.indexOf(searchValue[, fromIndex])
  • searchValue – สตริงที่ต้องการค้นหา
  • fromIndex (optional) – เริ่มค้นหาจาก index นี้ (default 0)

ตัวอย่างเพิ่มเติม

var str = "Hello World Hello";
str.indexOf("Hello");        // 0 (ตัวแรก)
str.indexOf("Hello", 1);     // 12 (ตัวที่สอง เริ่มค้นจาก index 1)
str.indexOf("World");        // 6
str.indexOf("JavaScript");   // -1 (ไม่พบ)

includes() (ES6) – แนะนำสำหรับแค่ตรวจสอบมี/ไม่มี

"hello world".includes("world"); // true
"hello world".includes("java");  // false

startsWith() / endsWith() (ES6)

"hello".startsWith("he"); // true
"hello".endsWith("lo");   // true