บทความนี้อธิบายวิธีการของ JavaScript เพื่อตรวจสอบว่าสตริงมีสตริงย่อยที่ระบุหรือไม่ แบ่งปันสำหรับการอ้างอิงของคุณ การวิเคราะห์เฉพาะมีดังนี้:
รหัส JS ต่อไปนี้กำหนดวิธีการที่มีสำหรับวัตถุสตริงเพื่อตรวจสอบว่าสตริงมีสตริงย่อยซึ่งมีประโยชน์มาก
if (! array.prototype.indexof) {array.prototype.indexof = function (obj, start) {สำหรับ (var i = (เริ่มต้น || 0), j = this.length; i <j; i ++) {ถ้า (นี้ }} return -1; }} if (! string.prototype.contains) {string.prototype.contains = function (arg) {return !! ~ this.indexof (arg); -ด้านล่างเป็นตัวอย่างการใช้โดยละเอียดที่สามารถดำเนินการในเบราว์เซอร์
คัดลอกรหัสดังนี้: ป้อนสองสตริงและตรวจสอบว่า Strign 1 มีสตริง 2 <br> <br>
สตริง 1: <อินพุต id = "foo" type = "text" value = "สุนัขจิ้งจอกสีน้ำตาลเร็วกระโดดข้าม"> <br>
สตริง 2: <อินพุต id = "bar" type = "text" value = "Fox Jumps"> <br> <br>
<ปุ่ม onclick = "checkstring ()"> คลิกเพื่อตรวจสอบว่าสตริง 1 มีสตริง 2 </pution>
<script>
if (! array.prototype.indexof) {
array.prototype.indexof = function (obj, start) {
สำหรับ (var i = (start || 0), j = this.length; i <j; i ++) {
ถ้า (นี่ [i] === obj) {return i; -
-
กลับ -1;
-
-
if (! string.prototype.contains) {
string.prototype.contains = function (arg) {
return !! ~ this.indexof (arg);
-
-
การตรวจสอบฟังก์ชัน () {
var foo = document.getElementById ("foo") ค่า;
var bar = document.getElementById ("bar"). ค่า;
การแจ้งเตือน (foo.contains (bar));
-
</script>
ฉันหวังว่าบทความนี้จะเป็นประโยชน์กับการเขียนโปรแกรม JavaScript ของทุกคน