2013-08-28 37 views
0

搜索字符串你好,我目前有我公司開發的這部分代碼,但我希望做一些編輯:使用Javascript - 從開始

$('#target').keydown(function(event) { 
if (event.which == 13) 
{ 
    var users = ["Dennis Lucky","Lucy Foo","Name Lastname","Billy Jean"]; 
    var match = 0; 
    var str = $('#target').val(); 

    for(i=0;i<users.length;i++) 
    { 
     if (users[i].toLowerCase().indexOf(str.toLowerCase()) > -1) 
     { 
      match++; 
      name = users[i]; 
     } 
    } 
    if(match == 1) 
    { 
     $('#target').val(''); 
     $('#chatbox').append('<span style="color:blue;">'+name+'</span>&nbsp;'); 
     console.log(name); 
    } 
    else if (match >= 2) 
    { 
     console.log("many entries"); 
    } 
}}); 

的想法是,如果我輸入的東西,砸,如果進入部分字符串存在於用戶變成藍色。有了這個代碼,我有問題,如果我寫「盧」我得到2結果,「丹尼斯幸運」和「露西富」。

我想改變我的代碼,所以當我輸入「Lu」時,它將開始搜索以此刺痛開始的單詞並且不包括它。

+0

拆分名稱和檢查索引是0 – rlemon

回答

0
if (users[i].toLowerCase().indexOf(str.toLowerCase()) > -1) 

如果indexOf的返回值大於-1,則條件爲真。在JavaScript中,如果在「haystack」(您正在搜索的字符串)中找不到匹配「needle」(您正在搜索的字符串),則indexOf返回-1。否則,它返回「乾草堆」中「針」的第一個索引。

解釋我的indexOf的術語,這裏有一個例子:

haystack.indexOf(needle); // How to use the indexOf function 
console.log("apples oranges apples".indexOf("apples")); // This would print 0. 
console.log("apples oranges apples".indexOf("white")); // This would print -1. 

如果你想確保字符串與「針」開始,你只需要更改您的代碼

if (users[i].toLowerCase().indexOf(str.toLowerCase()) == 0) 

如果你想要你的「單詞」(「Lucy Foo」將是「Lucy」和「Foo」),可以用空格字符來分割你的名字串,然後用結果數組的元素執行indexof搜索,或者轉向正則表達式。

+0

它應該是「Lucy Foo」作爲名字姓,所以在我的if語句中== 0非常棒!我發現正則表達式太複雜,你救了我很多麻煩:) – Dennis

+0

雖然更復雜,最終你不得不把它吸了起來,並學習它們。這裏有一個鏈接到在線正則表達式測試器來幫助調試/寫作。 http://regexpal.com/和http://www.regextester.com/ –