javascript - Regular expression to compare the first n characters of a string array -


i working on auto complete example , want words starting entered text.

eg:-if type "al" want first 2 results not 3rd one

**al**abama **al**aska c**al**lifornia 

if want fastest method (case insensitive):

var options = ['alabama', 'alaska', 'california', 'new york'];  function compare (string, ar) {     return ar.filter(function (a) {         return a.tolowercase().indexof(string.tolowercase())===0;     }); }  var results = compare('al', options); console.log( results ); 

results is:

["alabama", "alaska"]

this works going through options, checks if begin string, if do, keeps them


if want regex:

var options = ['alabama', 'alaska', 'california', 'new york'];  function compare (string, ar) {      return ar.filter(function (a) {          return (new regexp("^(?:" + string + ")", "i")).test(a);     });  }  var results = compare('al', options); console.log( results ); 


if want test 1 item, do:

function compare (a, b) {      return a.tolowercase().indexof(b.tolowercase())===0  } 

compare('al', 'alabama'); --> true

compare('al', 'alabama'); --> true

compare('al', 'california'); --> false


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -