Search code examples
javascriptjqueryregexlevenshtein-distance

Closest match in a select


I have a select element containing different titles; as an example:

<select name="titles">
  <option value="1">Mr.</option>
  <option value="2">Mrs.</option>
  <option value="3">Ms.</option>
  <option value="4">Dr.</option>
  [..]
</select>

Then I have a string that contains a user-submitted title (originally written in a freeform textbox). My task is to make selected the option in the select that corresponds to that title.

However, it occurs to me that users are sometimes stupid.

The user-supplied string I search with could be "dr." or "Dr" or something like that. I need to match it with the most relevant one (i.e. "Dr." instead of "Mr.", both of them close to say, "dr.").

How would I go about this? I've only ever done approximate matching with MySQL's LIKE and PHP's levenshtein(), neither of which to my understanding are rather relevant in JS.

jQuery 1.7.1 is available. IE6 compatibility doesn't concern me.

Thank you in advance!


Solution

  • If I'm not mistaken, the only reasonable (and acceptable) variations are capital letter / no capital letter at the beginning and a missing point character at the end.

    If that's the case then you can simply compare the user string to each of the items in the select with the above in mind:

    • Convert first character of user input to uppercase.
    • Add a . to the end of the string if the user string does not end with ..
    • Compare the modified user string with each of the elements in select and see if one matches.