DIV CSS 佈局教程網

為 JavaScript 字串加上 contains 方法,判斷是否包含子字串
編輯:JavaScript綜合知識     

檢查一個字串是否包含某段子字串,是很常見的操作。雖然可以靠 indexOf 判斷,但如果能像其他語言那樣直接呼叫 contains,寫起來會更直覺。本文就來為 String 物件擴充一個 contains 方法。

下面是完整的程式碼:

代碼如下:


1 2 3 4 5 6 7 8 9 10 11 12 13 if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(obj, start) { for (var i = (start || 0), j = this.length; i < j; i++) { if (this[i] === obj) { return i; } } return -1; } } if (!String.prototype.contains) { String.prototype.contains = function (arg) { return !!~this.indexOf(arg); }; }

這裡有個小技巧:!!~ 的寫法能把 indexOf 回傳的 -1 或正數轉成布林值——~ 是按位元取反,-1 取反後為 0,再經 !! 轉為 false;其餘索引取反後為非零,轉為 true。

下面是一個可在瀏覽器內執行的完整範例:

代碼如下:
Enter two strings and check if Strign 1 contains String 2.<br> <br>
String 1: <input id="foo" type="text" value="a quick brown fox jumps over"> <br>
String 2: <input id="bar" type="text" value="fox jumps"> <br><br>
<button onclick="checkstring()">Click to check if String 1 contains String 2</button>
<script>
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
}
if (!String.prototype.contains) {
String.prototype.contains = function (arg) {
return !!~this.indexOf(arg);
};
}
function checkstring() {
var foo = document.getElementById("foo").value;
var bar = document.getElementById("bar").value;
alert(foo.contains(bar));
}
</script>

 

希望本文所述能對你的 JavaScript 開發有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved