我遇到了條件問題。我想返回模式以字符串開頭的索引(如果找不到則返回-1)。如果第三個參數爲true,則搜索將區分大小寫,否則它不區分大小寫。如果JavaScript中的其他條件在函數中
Examples
index("abAB12","AB",true) returns 2 but index("abAB12","AB",false) returns 0
index("abAB12","BA",true) returns -1 and index("abAB12","BA",false) returns 1
任何想法我可以做到這一點?
這是到目前爲止我的代碼
var s = "abAB12"
var p = "AB"
var cs = true
function index(string, pattern, caseSensitive) {
if (pattern) {
var found = false;
if (caseSensitive = false) {
if (string.indexOf(pattern.) >= 0) {
found = true;
}
return (found);
else {
return ("");
}
} else if (caseSensitive = true) {
if (string.toLowerCase().indexOf(pattern.toLowerCase()) >= 0) {
found = true;
}
return (found);
} else {
return ("");
}
}
}
alert(index(s, p, cs));
小提琴在http://jsfiddle.net/AfDFb/1/