vue 搜索結(jié)果匹配關(guān)鍵字高亮

一、效果圖

搜索結(jié)果匹配關(guān)鍵字高亮.gif

二、代碼實現(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方法進行標(biāo)準(zhǔn)化):

<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 下標(biāo)開始的指定數(shù)目的字符。

語法
stringObject.substr(start,length)

注:ECMAscript 沒有對該方法進行標(biāo)準(zhǔn)化,因此反對使用它。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容