Javascript - search a string from beginning -
hello have part of code developed want edits:
$('#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> '); console.log(name); } else if (match >= 2) { console.log("many entries"); } }});
the idea if type , hit enter if partial string exists in users becomes blue color.with code have problem if write "lu" 2 results, "dennis lucky" , "lucy foo".
i want change code when type "lu" start searching words starting sting , not include it.
if ( users[i].tolowercase().indexof(str.tolowercase()) > -1 )
the condition true if indexof's returned value greater -1. in javascript, indexof returns -1 if match "needle" (the string you're searching for) isn't found in "haystack" (the string you're searching within). otherwise, returns first index of "needle" in "haystack".
to explain terminology of indexof, here's example:
haystack.indexof(needle); // how use indexof function console.log("apples oranges apples".indexof("apples")); // print 0. console.log("apples oranges apples".indexof("white")); // print -1.
if want ensure string starts "needle", need change code to
if ( users[i].tolowercase().indexof(str.tolowercase()) == 0 )
if want "words" ("lucy foo" "lucy" , "foo"), either split name strings space character , perform indexof search elements of resultant array, or turn regex.
Comments
Post a Comment