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>

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!

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.

The users are never stupid ;)

Before you do the matching I would first make transform my all letters to lowecase in my javascript, then i would look for dots (.) and mabye remove them or add them to you match-string (its your choise).

Hope that helps.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"

<html lang="en">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript" charset="utf-8" src=""></script>
    <!-- Date: 2012-04-05 -->
    <script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
        var title = "dr"
        $("#titles option").each(function(i, el) {
            var re = new RegExp(title, 'ig')
            if ($(el).html().match(re)) {
                $(el).attr("selected", "selected");
    <select name="titles" id="titles">
      <option value="1">Mr.</option>
      <option value="2">Mrs.</option>
      <option value="3">Ms.</option>
      <option value="4">Dr.</option>

And another solution to your issue - give your users exactly this form so they will have no chance to type in any wrong data.