"Blue Whale".indexOf("Blue"); // returns 0 "Blue Whale".indexOf("Blute"); // returns -1 "Blue Whale".indexOf("Whale", 0); // returns 5 "Blue Whale".indexOf("Whale", 5); // returns 5 "Blue Whale".indexOf("", 9); // returns 9 "Blue Whale".indexOf("", 10); // returns 10 "Blue Whale".indexOf("", 11); // returns 10 "Blue Whale".indexOf("", 11); // returns 10
"Blue Whale".indexOf("blue") // returns -1
var str = 'To be, or not to be, that is the question.'; var count = 0; var pos = str.indexOf('e'); while (pos !== -1) { count++; pos = str.indexOf('e', pos + 1); } console.log(count); // displays 4
本身實現簡單的indexOf():this
String.prototype.indexOf = function (searchElement) { var target = String(searchElement); var start = arguments.length > 1 ? Number(arguments[1]) : 0; start = start >>> 0; if (start < 0) { start = 0; } if (target == '') { return start >= this.length ? this.length : start; } if (start >= this.length) { return -1; } var s = start; var l = 0; while (s < this.length) { if (this.charAt(s) == target.charAt(l)) { var i = l++; var j = s++; while (i < target.length) { if (this.charAt(j) != target.charAt(i)) { l = 0; break; } i++; j++; } if (i == target.length) { return s-1; } } s++; } return -1; }
String.prototype.lastIndexOf()spa
lastIndexOf()方法返回指定值在調用該方法的字符串中最後出現的位置,若是沒找到則返回 -1。從該字符串的後面向前查找,從 fromIndex 處開始。prototype
"canal".lastIndexOf("a") // returns 3 "canal".lastIndexOf("a",2) // returns 1 "canal".lastIndexOf("a",0) // returns -1 "canal".lastIndexOf("x") // returns -1
本身實現簡單的lastIndexOf():code
String.prototype.lastIndexOf = function (searchElement) { var target = String(searchElement); var start = arguments.length > 1 ? Number(arguments[1]) : this.length; start = start >>> 0; if (start < 0) { start = 0; } if (start > this.length) { start = this.length; } if (target == '') { return start >= this.length ? this.length : start; } var s = start; var l = target.length - 1; if (s == this.length) { s--; } while (s > -1) { if (this.charAt(s) == target.charAt(l)) { var i = l--; var j = s--; while (i > -1) { if (this.charAt(j) != target.charAt(i)) { i = target.length - 1; break; } i--; j--; } if (i == -1) { return s+1; } } s--; } return -1; }