ใช้ Method String.prototype.search() ค้นหาตำแหน่งของ Substring หรือ Regex ใน String คืนค่า Index (0-based) หรือ -1 ถ้าไม่พบ
ตัวอย่าง
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>String Search</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 20px; font-weight: 500; }
</style>
</head>
<body>
<h1>Searching a string in JavaScript</h1>
<div class="sample">The spring season is about to come.</div>
<div style="color: green;" class="result"></div>
<button class="btn">CLICK HERE</button>
<h3> Click to find 'spring' in the above string </h3>
<script>
let btnEle = document.querySelector(".btn");
let sampleEle = document.querySelector(".sample").innerHTML;
let resEle = document.querySelector(".result");
btnEle.addEventListener("click", () => {
resEle.innerHTML = "The string spring is found at position " + sampleEle.search("spring");
});
</script>
</body>
</html>
คำอธิบาย
str.search("spring")คืนค่า 4 (Index ของ 's' ใน "spring")- รองรับ Regex:
str.search(/spring/i)(Case-insensitive) - ต่างจาก
indexOf(): search() รองรับ Regex, indexOf() ไม่รองรับ - ต่างจาก
match(): search() คืน Index, match() คืน Array ของผลลัพธ์
ผลลัพธ์
แสดง "The string spring is found at position 4"