一仗哨、效果圖
二澈侠、代碼實現(xiàn)
<input ref="searchInput" v-model="inputVal" type="text" placeholder="搜索目的地" />
第一種寫法:搜索不區(qū)分大小寫,使用slice()切分字符串推薦使用
:
<a class="text">
<span>{{item.name.slice(0,item.name.toLowerCase().indexOf(inputVal.toLowerCase()))}}</span><span
style="color:#2A70FE">{{item.name.slice(item.name.toLowerCase().indexOf(inputVal.toLowerCase()),item.name.toLowerCase().indexOf(inputVal.toLowerCase())+inputVal.length)}}</span><span>{{item.name.substr(item.name.toLowerCase().indexOf(inputVal.toLowerCase())+inputVal.length)}}</span>
</a>
第二種寫法:搜索不區(qū)分大小劫侧,使用substr()切分字符串不推薦使用(因為ECMAscript沒有對substr方法進行標準化)
:
<a class="text">
<span>{{item.name.substr(0,item.name.toLowerCase().indexOf(inputVal.toLowerCase()))}}</span><span
style="color:#2A70FE">{{item.name.substr(item.name.toLowerCase().indexOf(inputVal.toLowerCase()),inputVal.length)}}</span><span>{{item.name.substr(item.name.toLowerCase().indexOf(inputVal.toLowerCase())+inputVal.length)}}</span>
</a>
第三種寫法:搜索區(qū)分大小寫的寫法最好把substr再優(yōu)化為slice切分
:
<input ref="searchInput" v-model="inputVal" type="text" placeholder="搜索目的地" />
<a class="text">
<span>{{item.name.substr(0,item.name.indexOf(inputVal))}}</span><span style="color:#2A70FE">{{inputVal}}</span><span>{{item.name.substr(item.name.indexOf(inputVal)+inputVal.length)}}</span>
</a>
三、相關(guān)知識:
1哨啃、indexOf兼容烧栋,可以用以下代碼兼容,也可以使用polyfill
let Util = {};
/**
* 判斷瀏覽器是否支持indexOf 拳球,indexOf 為ecmaScript5新方法 IE8以下(包括IE8审姓, IE8只支持部分ecma5)不支持
*/
Util.support_indexOf = function () {
if (!Array.prototype.indexOf) {
// 新增indexOf方法
Array.prototype.indexOf = function (item) {
let result = -1;
let a_item = null;
if (this.length == 0) {
return result;
}
for (var i = 0, len = this.length; i < len; i++) {
a_item = this[i];
if (a_item === item) {
result = i;
break;
}
}
return result;
}
}
}
Util.support_indexOf();
2、slice() 方法
定義和用法
slice()
方法可提取字符串的某個部分祝峻,并以新的字符串返回被提取的部分魔吐。
語法
stringObject.slice(start,end)
返回值
一個新的字符串。包括字符串 stringObject 從 start 開始(包括 start)到 end 結(jié)束(不包括 end)為止的所有字符莱找。
3酬姆、 substr() 方法不推薦使用
定義和用法
substr()
方法可在字符串中抽取從 start 下標開始的指定數(shù)目的字符。
語法
stringObject.substr(start,length)
注:ECMAscript 沒有對該方法進行標準化宋距,因此反對使用它轴踱。